文章目录
Swagger 常用注解
Swagger 是一个规范和完整的框架,用于生成、描述、调用和可视化 RESTful 风格的 Web 服务。目标是使客户端和文件系统作为服务器以同样的速度来更新文件的方法,参数和模型紧密集成到服务器。简单来说,Swagger 是一款可以根据 RESTful 风格生成的生成的接口开发文档,并且支持做测试的一款中间软件。
在 SpringBoot 项目中引入的依赖如下:
<!-- Swagger2模块 -->
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>2.9.2</version>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>2.9.2</version>
</dependency>
1. @Api
作用:控制整个类生成接口信息的内容
位置:类上方,一般为 Controller 类上方
常用属性:
- tags:描述类的名称,说明该类的作用,非空时会覆盖 value 值(常用)
- value:作为tags的补充,描述类的作用,用的比较少
@Api(tags = "用户信息控制类", value = "/user")
@Slf4j
@RestController
@RequestMapping("/user")
public class UserController{
2. @ApiOperation
作用:对方法进行总体描述
位置:请求方法上方,一般为 Controller 类中的请求方法
常用属性:
- value:对方法的描述(常用)
- note:方法的提示信息
@ApiOperation(value = "方法的描述")
3. @ApiImplicitParam
作用:对单个请求参数进行描述说明
位置:方法上方 或 @ApiImplicitParams注解中
常用属性:
- name:参数名
- value:参数的说明与描述
- required:参数是否必填
- paramType:属性类型,header获取时使用@RequestHeader,query获取时使用@RequestParam,path获取时使用@PathVariable,body(请求体),form(普通表单提交)
- dataType:数据类型,默认为 String
- defaultValue:参数的默认值
@PostMapping("/getUser")
@ApiImplicitParam(name = "address", value = "地址", required = true, paramType= "query", dataType = "string")
public User getUser(@RequestParam String address){
如果希望在方法上配置多个参数时,使用 @ApiImplicitParams 注解进行配置。示例如下:
@ApiImplicitParams(value={
@ApiImplicitParam(name="id",value = "编号", required = true, dataType = "String"),
@ApiImplicitParam(name="name",value = "姓名",required = true, dataType = "String"),
@ApiImplicitParam(name = "address", value = "地址", required = true, dataType = "string")
})
@PostMapping("/getUser")
public User getUser(@RequestParam Integer id, @RequestParam String name, @RequestParam String address){
4. @ApiParam
作用:对参数进行描述说明
位置:请求方法的括号中被描述参数的前面
常用属性:
- name:参数名称
- value:参数的描述
- required:参数是否必填
public User getUser(Integer id, @ApiParam(value="姓名",required = true) String name, String address){
5. @ApiModel
作用:描述一个 Model 的信息
位置:类上方,一般为实体类或DTO
常用属性:
- value:名称
- description:对类信息的描述
@ApiModel(description = "用户信息")
@Data
public class User {
6. @ApiModelProperty
作用:描述一个 Model 的属性
位置:属性上方,和@ApiModel注解配套使用
常用属性:
- value:属性的描述
- name:重写属性名
- example:示例内容
@ApiModelProperty(value = "姓名", name = "name", example = "张三")
private String name;
7. @ApiResponse
作用:表示一个响应信息,一般用来描述错误信息
位置:用在请求的方法上,一般放在 @ApiResponses 里使用
属性:
- code:HTTP状态码
- message:描述信息
- response:抛出异常的类
@ApiResponses({
@ApiResponse(code = 200, message = "请求成功"),
@ApiResponse(code = 404, message = "请求路径错误或跳转路径错误")
})
@PostMapping("/getUser")
public User getUser(@RequestParam Integer id){