廢話不多說,swagger2就是接口的便捷文檔查詢頁面。
1、首先pom.xml引入依賴包
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>2.9.2</version>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>2.9.2</version>
</dependency>
2、在DemoApplication的同級package中創建配置類 包名刪除了,太多了。
package com.example.demo;
@Configuration
@EnableSwagger2
public class SwaggerConfig {
@Bean
public Docket createRestApi(){
return new Docket(DocumentationType.SWAGGER_2)
.pathMapping("/")
.select()
.apis(RequestHandlerSelectors.basePackage("com.example.demo.controller"))
.paths(PathSelectors.any())
.build()
.apiInfo(new ApiInfoBuilder()
.title("SpringBoot整合Swagger")
.description("項目接口的詳細信息")
.version("1.0.0")
.contact(new Contact("付華國", "byteyun.net", "[email protected]"))
.build()
);
}
}
此時如果我們不先進行定義接口直接運行的話,啓動項目:
訪問:注意你的端口號:http://localhost:8080/swagger-ui.html
3、接下來我們定義接口的配置說明
4、重新啓動項目刷新頁面:
接口參數說明:
@Api註解可以用來標記當前Controller的功能。
@ApiOperation註解用來標記一個方法的作用。
@ApiImplicitParam註解用來描述一個參數,可以配置參數的中文含義,也可以給參數設置默認值,這樣在接口測試的時候可以避免手動輸入。
如果有多個參數,則需要使用多個@ApiImplicitParam註解來描述,多個@ApiImplicitParam註解需要放在一個@ApiImplicitParams註解中。
需要注意的是,@ApiImplicitParam註解中雖然可以指定參數是必填的,但是卻不能代替@RequestParam(required = true),前者的必填只是在Swagger2框架內必填,拋棄了Swagger2,這個限制就沒用了,所以假如開發者需要指定一個參數必填,@RequestParam(required = true)註解還是不能省略。
如果參數是一個對象(例如上文的更新接口),對於參數的描述也可以放在實體類中。例如下面一段代碼:
@ApiModel
public class User {
@ApiModelProperty(value = "用戶id")
private Integer id;
@ApiModelProperty(value = "用戶名")
private String username;
@ApiModelProperty(value = "用戶地址")
private String address;
//getter/setter
}
接口參數示例說明:
整體的controller類:
package com.example.demo.controller;
@Api(tags = "用戶管理相關接口")
@RestController
@RequestMapping("/hello")
public class HelloController {
@Autowired
private UserService userService;
@ApiOperation("獲取用戶列表")
@GetMapping("/getUserList")
public List<UserBase> getUserList(){
return userService.getUserList();
}
@ApiOperation("添加用戶的接口")
@ApiImplicitParams({
@ApiImplicitParam(name = "username", value = "用戶名", defaultValue = "李四"),
@ApiImplicitParam(name = "address", value = "用戶地址", defaultValue = "深圳", required = true)
}
)
@PostMapping("/addUser")
public Map<String,Object> addUser(String username, @RequestParam(required = true) String address) {
return new HashMap<String, Object>();
}
@GetMapping("/getUserById")
@ApiOperation("根據id查詢用戶的接口")
@ApiImplicitParam(name = "id", value = "用戶id", defaultValue = "99", required = true)
public UserBase getUserById(@PathVariable String id) {
UserBase user = new UserBase();
user.setId(id);
return user;
}
@GetMapping("/index")
public String index(String id){
return id;
}
}
參考文檔地址:https://blog.csdn.net/u012702547/article/details/88775298