文章目录
概念
Swagger 是一款RESTFUL接口的文档在线自动生成 + 功能测试功能软件
手写API文档的劣势:
- 文档需要更新的时候,需要再次发送一份给前端,也就是文档更新交流不及时
- 接口返回结果不明确
- 不能直接在线测试接口,通常需要使用工具,比如postman
- 接口文档太多,不好管理
使用
导入依赖
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>2.2.2</version>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>2.2.2</version>
</dependency>
创建Swagger2配置类
- 使用**@Configuration**来表示该类是个配置类
- 使用**@EnableSwagger2**来启用Swagger2
@Configuration
@EnableSwagger2
public class Swagger2Config {
@Bean
public Docket createRestApi() {
return new Docket(DocumentationType.SWAGGER_2)
.apiInfo(apiInfo())
.select()
.apis(RequestHandlerSelectors.any())
//.apis(RequestHandlerSelectors.basePackage("com.newcsp.community.controller"))
.paths(PathSelectors.any())
.build();
}
private ApiInfo apiInfo() {
return new ApiInfoBuilder()
// 标题
.title("我的Swagger API文档")
// 描述
.description("构建API文档")
// 作者信息
.contact(new Contact("ThinkWon", "https://thinkwon.blog.youkuaiyun.com/", "thinkwon@163.com"))
// 服务网址
.termsOfServiceUrl("https://thinkwon.blog.youkuaiyun.com/")
// 版本
.version("1.0.0")
.build();
}
}
添加文档内容
Controller相关注解
@Api
用在请求的类上,表示对类的说明
示例:
@Api(tags = {"用户controller"})
public class UserController {}
接口相关注解
@ApiOperation
用在请求类的方法上,说明方法的用途和作用
示例:
@GetMapping("/list")
@ApiOperation(value = "查询用户列表")
public List<UserDTO> list() {
return list;
}
@ApiParam
用在方法,参数和字段上,一般用在请求体参数上,描述请求体信息
示例:
@PostMapping
@ApiOperation(value = "新增用户")
public Boolean insert(@RequestBody @ApiParam(name = "UserDTO", value = "新增用户参数") UserDTO userDTO) {
list.add(userDTO);
return true;
}
@ApiImplicitParams
用在请求的方法上,表示一组参数说明,里面是
@ApiImplicitParam
列表
@ApiImplicitParam
用在
@ApiImplicitParams
注解中,对请求参数的说明
示例:
@GetMapping("/page")
@ApiOperation(value = "分页查询问题列表")
@ApiImplicitParams({
@ApiImplicitParam(name = "pageNum", value = "当前页数"),
@ApiImplicitParam(name = "pageSize", value = "每页记录数")
})
public List<UserDTO> page(
@RequestParam(defaultValue = "1", required = false) Integer pageNum, @RequestParam(defaultValue = "10", required = false) Integer pageSize) {
return list;
}
@ApiResponses
用在请求的方法上,表示一组响应
@ApiResponse
用在
@ApiResponses
中,一般用于表达一个错误的响应信息
示例:
@PutMapping
@ApiOperation(value = "更新用户信息")
@ApiResponses({
@ApiResponse(code = 400, message = "请求参数没填好"),
@ApiResponse(code = 404, message = "请求路径没有或页面跳转路径不对")
})
public Boolean update(@RequestBody @ApiParam(name = "UserDTO", value = "更新用户参数") UserDTO userDTO) {}
Model类相关注解
@ApiModel
用在实体类(模型)上,表示相关实体的描述
示例:
@ApiModel(value = "用户", description = "查询用户")
public class UserDTO implements Serializable
@ApiModelProperty
用在实体类属性上,表示属性的相关描述
示例:
@ApiModelProperty(value = "用户id")
private Integer userId;
@ApiModelProperty(value = "用户名")
private String username;
打开网址
查看网页端接口文档:http://localhost:8080/swagger-ui.html