第一步嘀略,導(dǎo)入swagger依賴:
<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>
第二步钮蛛,創(chuàng)建一個SwaggerConfig類:
@Configuration
@EnableSwagger2
public class SwaggerConfig {
@Bean
public Docket createRestApi() {
return new Docket(DocumentationType.SWAGGER_2)
.pathMapping("/")
.select()
.apis(RequestHandlerSelectors.basePackage("com.zhangyu.coderman.web.controller"))
.paths(PathSelectors.any())
.build().apiInfo(new ApiInfoBuilder()
.title("社區(qū)圈接口文檔")
.description("SpringBoot整合Swagger糯景,詳細(xì)信息......")
.version("1.0")
.contact(new Contact("前端頁面地址","http://localhost:8081/",""))
.license("The Apache License")
.licenseUrl("http://www.baidu.com")
.build());
}
}
這里的配置類通過@EnableSwagger2注解啟用Swagger2,然后配置一個Docket Bean膨俐,這個Bean中缩歪,配置映射路徑和要掃描的接口的位置归薛,在apiInfo中谍憔,主要配置一下Swagger2文檔網(wǎng)站的信息匪蝙,例如網(wǎng)站的標(biāo)題,網(wǎng)站的描述习贫,聯(lián)系人的信息逛球,使用的協(xié)議等等。
第三步苫昌,通過http://localhost:8080/swagger-ui.html訪問接口文檔
如果顯示以上頁面就表示配置成功了
第四步颤绕,為接口添加描述
@RestController
@Api(tags = "用戶管理相關(guān)接口")
@RequestMapping("/user")
public class UserController {
@PostMapping("/")
@ApiOperation("添加用戶的接口")
@ApiImplicitParams({
@ApiImplicitParam(name = "username", value = "用戶名", defaultValue = "李四"),
@ApiImplicitParam(name = "address", value = "用戶地址", defaultValue = "深圳", required = true)
}
)
public RespBean addUser(String username, @RequestParam(required = true) String address) {
return new RespBean();
}
@GetMapping("/")
@ApiOperation("根據(jù)id查詢用戶的接口")
@ApiImplicitParam(name = "id", value = "用戶id", defaultValue = "99", required = true)
public User getUserById(@PathVariable Integer id) {
User user = new User();
user.setId(id);
return user;
}
@PutMapping("/{id}")
@ApiOperation("根據(jù)id更新用戶的接口")
public User updateUserById(@RequestBody User user) {
return user;
}
}
- @Api注解可以用來標(biāo)記當(dāng)前Controller的功能。
- @ApiOperation注解用來標(biāo)記一個方法的作用祟身。
- @ApiImplicitParam注解用來描述一個參數(shù)奥务,可以配置參數(shù)的中文含義,也可以給參數(shù)設(shè)置默認(rèn)值袜硫,這樣在接口測試的時候可以避免手動輸入氯葬。
- 如果有多個參數(shù),則需要使用多個@ApiImplicitParam注解來描述婉陷,多個@ApiImplicitParam注解需要放在一個@ApiImplicitParams注解中帚称。
- 注解還可以加在實體類中:
@ApiModel
public class User {
@ApiModelProperty(value = "用戶id")
private Integer id;
@ApiModelProperty(value = "用戶名")
private String username;
@ApiModelProperty(value = "用戶地址")
private String address;
//getter/setter
}