【工具】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


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM