Swagger 注解使用代码片段

Knife官网https://doc.xiaominfo.com/knife4j/

@Api

@Api 用在类上,说明该类的作用。可以标记一个 Controller 类作为 Swagger 文档资源,使用方式代码如下所示。
@Api(tags={"用户接口"}) 
public class UserController { 

}
  • tags:接口说明,可以在页面中显示。可以配置多个,当配置多个的时候,在页面中会显示多个接口的信息。

@ApiModel

@ApiModel 用在类上,表示对类进行说明,用于实体类中的参数接收说明。
@ApiModel(value = "com.biancheng.auth.param.AddUserParam", description = "新增用户参数")
public class AddUserParam { 
}

@ApiModelProperty

@ApiModelProperty() 用于字段,表示对 model 属性的说明。
@ApiModel(value = "com.biancheng.auth.param.AddUserParam", description = "新增用户参数") 
public class AddUserParam { 
    @ApiModelProperty(value = "ID") 
    private String id; 
    
    @ApiModelProperty(value = "名称") 
    private String name; 
    
    @ApiModelProperty(value = "年龄") 
    private int age; 
}

@ApiModelProperty 具体有哪些字段参考其 API 文档,类似于 @ApiImplicitParam 见下方。

@ApiParam

@ApiParam 用于 Controller 中方法的参数说明。
@PostMapping("/user") 
public UserDto addUser(
    @ApiParam(value = "新增用户参数", required = true) @RequestBody AddUserParam param) {
    System.err.println(param.getName()); 
    return new UserDto();
}

@ApiOperation

@ApiOperation 用在 Controller 里的方法上,说明方法的作用,每一个接口的定义。
@ApiOperation(value="新增用户", notes="详细描述") 
public UserDto addUser(
    @ApiParam(value = "新增用户参数", required = true) @RequestBody AddUserParam param) { 
    
}
  • value:接口名称
  • notes:详细说明

@ApiResponse 和 @ApiResponses

@ApiResponse 用于方法上,说明接口响应的一些信息;@ApiResponses 组装了多个 @ApiResponse。使用方式代码如下所示。
@ApiResponses({ 
    @ApiResponse(code = 200, message = "OK", response = UserDto.class) 
}) 
@PostMapping("/user") 
public UserDto addUser(
    @ApiParam(value = "新增用户参数", required = true) @RequestBody AddUserParam param) { 

}
  • code http的状态码
  • message 描述
  • response 默认响应类 Void
  • reference 参考ApiOperation中配置
  • responseHeaders 参考 ResponseHeader 属性配置说明
  • responseContainer 参考ApiOperation中配置

@ApiImplicitParam 和 @ApiImplicitParams

用在方法上,为单独的请求参数进行说明。使用方式代码如下所示。
@ApiImplicitParams({ 
    @ApiImplicitParam(name = "id", value = "用户ID", dataType = "string", paramType = "query", required = true, defaultValue = "1") 
}) 
@ApiResponses({ 
    @ApiResponse(code = 200, message = "OK", response = UserDto.class) 
}) 
@GetMapping("/user") 
public UserDto getUser(@RequestParam("id") String id) { 
    return new UserDto(); 
}
  • name:参数名,对应方法中单独的参数名称
  • value:参数的中文说明
  • required:是否必填
  • paramType:参数类型(有以下分类)
    • path 【restful 路径参数,后端用 @PathVariable 标记接收参数】
    • query 【查询字符串,后端用 @RequestParam 标记接收参数】
    • body 【请求体参数,后端用 @RequestBody 标记接收参数,多媒体资源 Multipart】
    • header 【请求头参数,后端用 @RequestHeader 标记】
    • form 【表单提交,表单提交参数映射取决于如何传输】
  • dataType:参数数据类型
    • string
    • integer(int64)
    • 可以是类名
  • defaultValue:默认值
  • allowableValues:限制此参数的可接受值
    • "first,second,third"
    • "range[1,5]" "range(1,5)" "range[1,5)" 极限最大最小边界:infinity / -infinity

 

 

posted on 2022-02-19 10:52  guardianbo  阅读(185)  评论(0编辑  收藏  举报

导航