swagger2 注解、快速使用

7 篇文章 0 订阅

swagger2 自动生成注解,可以极大提高API的编写质量和速度,提高工作效率。

一、注解

  • @Api() 用于类

标识该类是swagger下的资源
tags–表示说明
value–也是说明,可以使用tags替代
但是tags如果有多个值,会生成多个list

@Api(value="XXcontroller",tags={"xxx接口"})
@RestController
public class xxController {
}
  • @ApiOperation() 用于方法

表示一个http请求的操作
value用于方法描述
notes用于提示内容
tags可以重新分组(视情况而用)

  • @ApiParam() 用于方法,参数,字段说明

表示对参数的添加元数据(说明或是否必填等)
name–参数名
value–参数说明
required–是否必填

@Api(value="用户controller",tags={"用户操作接口"})
@RestController
public class UserController {
     @ApiOperation(value="获取用户信息",tags={"获取用户信息copy"},notes="注意问题点")
     @GetMapping("/getUserInfo")
     public User getUserInfo(@ApiParam(name="id",value="用户id",required=true) Long id,@ApiParam(name="username",value="用户名") String username) {
     // userService可忽略,是业务逻辑
      User user = userService.getUserInfo();

      return user;
  }
}
  • @ApiModel() 用于类

表示对类进行说明,用于参数用实体类接收
value–表示对象名
description–描述
都可省略

  • @ApiModelProperty() 用于方法,字段

表示对model属性的说明或者数据操作更改
value–字段说明
name–重写属性名字
dataType–重写属性类型
required–是否必填
example–举例说明
hidden–隐藏

@ApiModel(value="user对象",description="用户对象user")
public class User implements Serializable{
    private static final long serialVersionUID = 1L;
     @ApiModelProperty(value="用户名",name="username",example="xingguo")
     private String username;
     @ApiModelProperty(value="状态",name="state",required=true)
      private Integer state;
      private String password;
      private String nickName;
      private Integer isDeleted;

      @ApiModelProperty(value="id数组",hidden=true)
      private String[] ids;
      private List<String> idList;
     //省略get/set
}

@ApiOperation("更改用户信息")
  @PostMapping("/updateUserInfo")
  public int updateUserInfo(@RequestBody @ApiParam(name="用户对象",value="传入json格式",required=true) User user){

     int num = userService.updateUserInfo(user);
     return num;
  }
  • @ApiIgnore() 用于类,方法,方法参数

表示这个方法或者类被忽略 ,不被swagger显示在页面上

  • @ApiImplicitParam() 用于方法

表示单独的请求参数

  • @ApiImplicitParams() 用于方法,包含多个 @ApiImplicitParam

name–参数ming
value–参数说明
dataType–数据类型
paramType–参数类型
example–举例说明

@ApiOperation("查询测试")
  @GetMapping("select")
  //@ApiImplicitParam(name="name",value="用户名",dataType="String", paramType = "query")
  @ApiImplicitParams({
  @ApiImplicitParam(name="name",value="用户名",dataType="string", paramType = "query",example="xingguo"),
  @ApiImplicitParam(name="id",value="用户id",dataType="long", paramType = "query")})
  public void select(){

  }
  • @ApiResponse() 用于方法

code-整形,错误码
message,错误描述

  • @ApiResponses() 用于方法,包含多个 @ApiResponse

返回结果说明
value ,{}

@ApiOperation(value = "XXXX", notes = "xxxxxxxxxxxxxxxxxxxxxxxx", response = String.class)
    @ApiResponses(value = {
            @ApiResponse(code = 200, message = "Successful — 请求已完成"),
            @ApiResponse(code = 400, message = "请求中有语法问题,或不能满足请求"),
            @ApiResponse(code = 401, message = "未授权客户机访问数据"),
            @ApiResponse(code = 404, message = "服务器找不到给定的资源;文档不存在"),
            @ApiResponse(code = 500, message = "服务器不能完成请求")}
    )
    @ResponseBody
    @RequestMapping(value = "/test", method = {RequestMethod.PUT,RequestMethod.PATCH})
    public String XXXXXXX(@RequestBody String parameter)
            throws Exception {
        logger.info("## 请求时间:{}", new Date());
        return "";
    }
}

二、快速使用

  1. Maven依赖
<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.配置类(springboot)

@Configuration
@EnableSwagger2
public class SwaggerConfig {
    @Bean
    public Docket customDocket() {
        return new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(apiInfo())
                .select()
                .apis(RequestHandlerSelectors.any())
                .paths(PathSelectors.any())
                .build();
    }

    private ApiInfo apiInfo() {
        Contact contact = new Contact("团队名", "www.my.com", "my@my.com");
        return new ApiInfoBuilder()
                .title("文档标题")
                .description("文档描述")
                .contact(contact)   // 联系方式
                .version("1.1.0")  // 版本
                .build();
    }
}
  1. spring mvc配置
<bean class="com.hogen.config.SwaggerConfig"></bean>
<mvc:default-servlet-handler/>
<!-- 根据profile配置不同的location,就可以在生产环境中禁用Swagger -->
<mvc:resources mapping="swagger-ui.html" location="classpath:/META-INF/resources/"/> 
<mvc:resources mapping="/webjars/**" location="classpath:/META-INF/resources/webjars/"/>
  1. 使用示例:注解标注Controller
@Api(value="用户controller",tags={"用户操作接口"})
@RestController
public class UserController {
     @ApiOperation(value="获取用户信息",tags={"获取用户信息copy"},notes="注意问题点")
     @GetMapping("/getUserInfo")
     public User getUserInfo(@ApiParam(name="id",value="用户id",required=true) Long id,@ApiParam(name="username",value="用户名") String username) {
     // userService可忽略,是业务逻辑
      User user = userService.getUserInfo();

      return user;
  }
}
  1. 文档访问
ip:port/swagger-ui.html
  1. swagger2导出的文档可以通过Swagger Editor打开
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值