【工具】Swagger2写接口注释

一、遇到的问题

作为一名coder,经常需要向别人提供接口,或者调用别人的接口。于是就有了接口参数是什么意思,要怎么传参数,返回值是什么意思……有多少调用方,就会有多少人来询问这些参数。如果是长时间之后,自己或许都不知道这些参数是什么意思。于是维护接口文档便成了一项必不可少的工作,维护文档也有很多问题:

  • 如果手工写会很费劲
  • 接口变更后可能会忘了同步文档
  • ……

二、Swagger配置

Swagger(官方文档)可以快速帮助实现接口api的维护与简单测试。

a、引入maven依赖包

    <dependency>
      <groupId>io.springfox</groupId>
      <artifactId>springfox-swagger2</artifactId>
      <version>2.5.0</version>
    </dependency>
    <dependency>
      <groupId>io.springfox</groupId>
      <artifactId>springfox-swagger-ui</artifactId>
      <version>2.5.0</version>
    </dependency>

b、配置Swagger

@Configuration
@EnableSwagger2
@Profile("dev")
public class SwaggerConfig { public static final String SWAGGER_SCAN_BASE_PACKAGE = "api.doc.demo.controller"; public static final String VERSION = "1.0.0"; @Bean public Docket createRestApi() { return new Docket(DocumentationType.SWAGGER_2) .apiInfo(apiInfo()) .select() /**api接口包扫描路径*/ .apis(RequestHandlerSelectors.basePackage(SWAGGER_SCAN_BASE_PACKAGE)) /**可以根据url路径设置哪些请求加入文档,忽略哪些请求*/ .paths(PathSelectors.any()) .build(); } private ApiInfo apiInfo() { return new ApiInfoBuilder() /**设置文档的标题*/ .title("Swagger2 接口文档示例") /**设置文档的描述*/ .description("更多内容请关注:http://www.abc.com") /**设置文档的联系方式*/ .contact(new Contact("create by XXX", "http://www.abc.com", "xxxx.@xxx.com")) /**设置文档的License信息->1.3 License information*/ .termsOfServiceUrl("www.abc.com") .license("xxx") .licenseUrl("http://www.xxx.com") /**设置文档的版本信息-> 1.1 Version information*/ .version(VERSION) .build(); } }

c、常用注解

  • @ApiOperation : api说明
    @ApiOperation(value="获取用户列表", notes="获取所有用户列表",produces = "application/json")
    @RequestMapping(value="/getList", method= RequestMethod.GET)
    public List<UserModel> getUserList() {
        return getDemoList();
    }

  • @ApiResponses :默认Response的基础上增加新的Response说明
  • @ApiImplicitParam : 描述接口参数
@ApiImplicitParam(name = "userId",value = "用户ID",dataType = "int",paramType = "path")
  • @ApiImplicitParams : 多个参数
@ApiImplicitParams({
@ApiImplicitParam(name = "id",value = "用户ID",paramType = "path",dataType = "int"),
@ApiImplicitParam(name = "userName",value = "用户名称",paramType = "form",dataType = "string")
})
  •  @ApiModel : model属性
@ApiModel(value = "user", description = "user对象")
public class UserModel {
@ApiModelProperty(value = "ID", dataType = "Integer", required = true)
private Integer userId;
@ApiModelProperty(value = "用戶名", dataType = "String")
private String userName;
@ApiModelProperty(value = "性別", dataType = "Integer", allowableValues = "0,1,2")
private Integer sex;
}

这样就可以通过访问 http://localhost:8080/swagger-ui.html 看到接口API调用说明。demo

原文地址:https://www.cnblogs.com/mr-yang-localhost/p/8331758.html