使用Swagger2自動生成API接口文檔


一、為什么使用Swagger2

當下很多公司都采取前后端分離的開發模式,前端和后端的工作由不同的工程師完成。在這種開發模式下,維持一份及時更新且完整的 Rest API 文檔將會極大的提高我們的工作效率。傳統意義上的文檔都是后端開發人員手動編寫的,相信大家也都知道這種方式很難保證文檔的及時性,這種文檔久而久之也就會失去其參考意義,反而還會加大我們的溝通成本。而 Swagger 給我們提供了一個全新的維護 API 文檔的方式,下面我們就來了解一下它的優點:

1、代碼變,文檔變。只需要少量的注解,Swagger 就可以根據代碼自動生成 API 文檔,很好的保證了文檔的時效性。

2、跨語言性,支持 40 多種語言。

3、Swagger UI 呈現出來的是一份可交互式的 API 文檔,我們可以直接在文檔頁面嘗試 API 的調用,省去了准備復雜的調用參數的過程。

4、還可以將文檔規范導入相關的工具(例如 Postman、SoapUI), 這些工具將會為我們自動地創建自動化測試。

二、配置使用Swagger2

1、在pom.xml加入swagger2相關依賴

復制代碼
 1 <!--swagger2的依賴-->
 2 <dependency>
 3    <groupId>io.springfox</groupId>
 4    <artifactId>springfox-swagger2</artifactId>
 5    <version>2.9.2</version>
 6 </dependency>
 7 <dependency>
 8    <groupId>io.springfox</groupId>
 9    <artifactId>springfox-swagger-ui</artifactId>
10    <version>2.9.2</version>
11 </dependency>
復制代碼

 

2、新建Swagger2Config配置類

復制代碼
 1 import io.swagger.annotations.Api;
 2 import org.springframework.context.annotation.Bean;
 3 import org.springframework.context.annotation.Configuration;
 4 import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
 5 import org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport;
 6 import springfox.documentation.builders.ApiInfoBuilder;
 7 import springfox.documentation.builders.PathSelectors;
 8 import springfox.documentation.builders.RequestHandlerSelectors;
 9 import springfox.documentation.service.*;
10 import springfox.documentation.spi.DocumentationType;
11 import springfox.documentation.spi.service.contexts.SecurityContext;
12 import springfox.documentation.spring.web.plugins.Docket;
13 import springfox.documentation.swagger2.annotations.EnableSwagger2;
14 
15 import java.util.ArrayList;
16 import java.util.List;
17 
18 /**
19  * @author yunqing
20  * @date 2019/12/17 10:23
21  */
22 @Configuration
23 @EnableSwagger2
24 public class Swagger2Config extends WebMvcConfigurationSupport {
25     @Bean
26     public Docket createRestApi(){
27         return new Docket(DocumentationType.SWAGGER_2)
28                 .apiInfo(apiInfo())
29                 .select()
30                 //為當前包下controller生成API文檔
31 //                .apis(RequestHandlerSelectors.basePackage("com.troila"))
32                 //為有@Api注解的Controller生成API文檔
33 //                .apis(RequestHandlerSelectors.withClassAnnotation(Api.class))
34                 //為有@ApiOperation注解的方法生成API文檔
35 //                .apis(RequestHandlerSelectors.withMethodAnnotation(ApiOperation.class))
36                 //為任何接口生成API文檔
37                 .apis(RequestHandlerSelectors.any())
38                 .paths(PathSelectors.any())
39                 .build();
40                 //添加登錄認證
41                 /*.securitySchemes(securitySchemes())
42                 .securityContexts(securityContexts());*/
43     }
44 
45     private ApiInfo apiInfo() {
46         Contact contact = new Contact("yunqing", "", "yunqing****@gmail.com");
47         return new ApiInfoBuilder()
48                 .title("SwaggerUI演示")
49                 .description("接口文檔,描述詞省略200字")
50                 .contact(contact)
51                 .version("1.0")
52                 .build();
53     }
54 
55     /**
56      * 配置swagger2的靜態資源路徑
57      * @param registry
58      */
59     @Override
60     protected void addResourceHandlers(ResourceHandlerRegistry registry) {
61         // 解決靜態資源無法訪問
62         registry.addResourceHandler("/**")
63                 .addResourceLocations("classpath:/static/");
64         // 解決swagger無法訪問
65         registry.addResourceHandler("/swagger-ui.html")
66                 .addResourceLocations("classpath:/META-INF/resources/");
67         // 解決swagger的js文件無法訪問
68         registry.addResourceHandler("/webjars/**")
69                 .addResourceLocations("classpath:/META-INF/resources/webjars/");
70     }
71 
72 
73     /**
74      * 給API文檔接口添加安全認證
75      */
76     /*private List<ApiKey> securitySchemes() {
77         List<ApiKey> apiKeys = new ArrayList<>();
78         apiKeys.add(new ApiKey("Authorization", "Authorization", "header"));
79         return apiKeys;
80     }
81 
82     private List<SecurityContext> securityContexts() {
83         List<SecurityContext> securityContexts = new ArrayList<>();
84         securityContexts.add(SecurityContext.builder()
85                 .securityReferences(defaultAuth())
86                 .forPaths(PathSelectors.regex("^(?!auth).*$")).build());
87         return securityContexts;
88     }
89 
90     private List<SecurityReference> defaultAuth() {
91         AuthorizationScope authorizationScope = new AuthorizationScope("global", "accessEverything");
92         AuthorizationScope[] authorizationScopes = new AuthorizationScope[1];
93         authorizationScopes[0] = authorizationScope;
94         List<SecurityReference> securityReferences = new ArrayList<>();
95         securityReferences.add(new SecurityReference("Authorization", authorizationScopes));
96         return securityReferences;
97     }*/
98 }
復制代碼

 

3、在shiro配置類中放行swagger2相關資源

1 //swagger2免攔截
2 filterChainDefinitionMap.put("/swagger-ui.html**", "anon");
3 filterChainDefinitionMap.put("/v2/api-docs", "anon");
4 filterChainDefinitionMap.put("/swagger-resources/**", "anon");
5 filterChainDefinitionMap.put("/webjars/**", "anon");

 

4、配置為哪部分接口生成API文檔

主要是在Swagger2Config配置類中進行createRestApi()方法中進行配置,下面提供四種配置:

①為任何接口生成API文檔,這種方式不必在接口方法上加任何注解,方便的同時也會因為沒有添加任何注解所以生成的API文檔也沒有注釋,可讀性不高。

復制代碼
 1 @Bean
 2     public Docket createRestApi(){
 3         return new Docket(DocumentationType.SWAGGER_2)
 4                 .apiInfo(apiInfo())
 5                 .select()
 6                 //為任何接口生成API文檔
 7                 .apis(RequestHandlerSelectors.any())
 8                 .paths(PathSelectors.any())
 9                 .build();
10     }
復制代碼

 

②為當前配置的包下controller生成API文檔

.apis(RequestHandlerSelectors.basePackage("com.troila"))

 

③為有@Api注解的Controller生成API文檔

.apis(RequestHandlerSelectors.withClassAnnotation(Api.class))

 

④為有@ApiOperation注解的方法生成API文檔

.apis(RequestHandlerSelectors.withMethodAnnotation(ApiOperation.class))

三、Swagger2注解詳解

1、@Api :請求類的說明

@Api:放在請求的類上,與 @Controller 並列,說明類的作用,如用戶模塊,訂單類等。
    tags="說明該類的作用"
    value="該參數沒什么意義,所以不需要配置"

舉例:

復制代碼
1 @Api(tags = "賬戶相關模塊")
2 @RestController
3 @RequestMapping("/api/account")
4 public class AccountController {
5     //TODO
6 }
復制代碼

 

2、@ApiOperation:方法的說明

@ApiOperation:"用在請求的方法上,說明方法的作用"
    value="說明方法的作用"
    notes="方法的備注說明"

舉例:

復制代碼
1 @ApiOperation(value = "修改密碼", notes = "方法的備注說明,如果有可以寫在這里")
2 @PostMapping("/changepass")
3 public AjaxResult changePassword(@AutosetParam SessionInfo sessionInfo,
4         @RequestBody @Valid PasswordModel passwordModel) {
5     //TODO
6 }
復制代碼

3、@ApiImplicitParams、@ApiImplicitParam:方法參數的說明

復制代碼
@ApiImplicitParams:用在請求的方法上,包含一組參數說明
    @ApiImplicitParam:對單個參數的說明      
        name:參數名
        value:參數的漢字說明、解釋
        required:參數是否必須傳
        paramType:參數放在哪個地方
            · header --> 請求參數的獲取:@RequestHeader
            · query --> 請求參數的獲取:@RequestParam
            · path(用於restful接口)--> 請求參數的獲取:@PathVariable
            · body(請求體)-->  @RequestBody User user
            · form(普通表單提交)     
        dataType:參數類型,默認String,其它值dataType="int"       
        defaultValue:參數的默認值
復制代碼

 

舉例:

復制代碼
 1 @ApiOperation(value="用戶登錄",notes="隨邊說點啥")
 2 @ApiImplicitParams({
 3         @ApiImplicitParam(name="mobile",value="手機號",required=true,paramType="form"),
 4         @ApiImplicitParam(name="password",value="密碼",required=true,paramType="form"),
 5         @ApiImplicitParam(name="age",value="年齡",required=true,paramType="form",dataType="Integer")
 6 })
 7 @PostMapping("/login")
 8 public AjaxResult login(@RequestParam String mobile, @RequestParam String password,
 9                         @RequestParam Integer age){
10     //TODO
11     return AjaxResult.OK();
12 }
復制代碼

 

單個參數舉例

復制代碼
@ApiOperation("根據部門Id刪除")
@ApiImplicitParam(name="depId",value="部門id",required=true,paramType="query")
@GetMapping("/delete")
public AjaxResult delete(String depId) {
    //TODO
}
復制代碼

 

4、@ApiResponses、@ApiResponse:方法返回值的說明

@ApiResponses:方法返回對象的說明
    @ApiResponse:每個參數的說明
        code:數字,例如400
        message:信息,例如"請求參數沒填好"
        response:拋出異常的類

舉例:

復制代碼
 1 @ApiOperation(value = "修改密碼", notes = "方法的備注說明,如果有可以寫在這里")
 2 @ApiResponses({
 3         @ApiResponse(code = 400, message = "請求參數沒填好"),
 4         @ApiResponse(code = 404, message = "請求路徑找不到")
 5 })
 6 @PostMapping("/changepass")
 7 public AjaxResult changePassword(@AutosetParam SessionInfo sessionInfo,
 8         @RequestBody @Valid PasswordModel passwordModel) {
 9     //TODO
10 }
復制代碼

 

5、@ApiModel:用於JavaBean上面,表示一個JavaBean

@ApiModel:用於JavaBean的類上面,表示此 JavaBean 整體的信息
    (這種一般用在post創建的時候,使用 @RequestBody 這樣的場景,請求參數無法使用 @ApiImplicitParam 注解進行描述的時候 )

 

6. @ApiModelProperty:用在JavaBean的屬性上面,說明屬性的含義

@ApiModel和 @ApiModelProperty舉例:

復制代碼
1 @ApiModel("修改密碼所需參數封裝類")
2 public class PasswordModel
3 {
4     @ApiModelProperty("賬戶Id")
5     private String accountId;
6 //TODO
7 }
復制代碼

總結:API文檔瀏覽地址

配置好Swagger2並適當添加注解后,啟動SpringBoot應用,
訪問http://localhost:8080/swagger-ui.html 即可瀏覽API文檔。
另外,我們需要為了API文檔的可讀性,適當的使用以上幾種注解就可以。

 

 

四、把Swagger2的API接口導入Postman

1、訪問http://localhost:8080/swagger-ui.html 文檔的首頁,復制下面這個地址

 

2.打開postman-->import-->import Form Link

 

 

 

 

 

 

轉載:https://zhuanlan.zhihu.com/p/98075551


免責聲明!

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



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