1. 程式人生 > >Springboot整合swagger2生成介面文件

Springboot整合swagger2生成介面文件

【轉載請註明】:

原文出處:https://www.cnblogs.com/jstarseven/p/11509884.html    作者:jstarseven    碼字挺辛苦的.....  


 

一、Swagger介紹

Swagger是一個規範和完整的框架,用於生成、描述、呼叫和視覺化RESTful風格的web服務。目標是使客戶端和檔案系統作為伺服器以同樣的速度來更新檔案的方法,引數和模型緊密整合到伺服器。這個解釋簡單點來講就是說,swagger是一款可以根據restful風格生成的介面開發文件,並且支援做測試的一款中間軟體。

  

二、使用swagger優勢

1、對於後端開發人員來說

  • 不用再手寫Wiki介面拼大量引數,避免手寫錯誤
  • 對程式碼侵入性低,採用全註解的方式,開發簡單
  • 方法引數名修改、新增、減少引數都可以直接生效,不用手動維護
  • 缺點:增加了開發成本,寫介面還得再寫一套引數配置

 

2、對前端開發來說

  • 後端只需要定義好介面,會自動生成文件,介面功能、引數一目瞭然
  • 聯調方便,如果出了問題,直接測試介面,實時檢查引數和返回值,就可以快速定位是前端還是後端的問題

 

3、對於測試來說

  • 但對於測試沒有前端介面UI的功能,可以直接用它來測試介面
  • 操作簡單,不用瞭解具體程式碼就可以操作

 

三、springboot整合swagger使用

1、新建maven專案(結構如下:)

 

2、配置pom.xml檔案

 1 <?xml version="1.0" encoding="UTF-8"?>
 2 <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 3          xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
 4     <modelVersion>4.0.0</modelVersion>
 5     <parent>
 6         <groupId>org.springframework.boot</groupId>
 7         <artifactId>spring-boot-starter-parent</artifactId>
 8         <version>2.1.3.RELEASE</version>
 9         <relativePath/>
10     </parent>
11     <groupId>com.dds.sbswagger</groupId>
12     <artifactId>sb-swagger</artifactId>
13     <version>0.0.1-SNAPSHOT</version>
14     <name>sb-swagger</name>
15     <description>Demo project for Spring Boot</description>
16 
17     <properties>
18         <java.version>1.8</java.version>
19     </properties>
20     <dependencies>
21         <dependency>
22             <groupId>org.springframework.boot</groupId>
23             <artifactId>spring-boot-starter-web</artifactId>
24         </dependency>
25         <dependency>
26             <groupId>org.springframework.boot</groupId>
27             <artifactId>spring-boot-starter-test</artifactId>
28             <scope>test</scope>
29         </dependency>
30         <dependency>
31             <groupId>io.springfox</groupId>
32             <artifactId>springfox-swagger2</artifactId>
33             <version>2.9.2</version>
34         </dependency>
35         <dependency>
36             <groupId>io.springfox</groupId>
37             <artifactId>springfox-swagger-ui</artifactId>
38             <version>2.9.2</version>
39         </dependency>
40         <dependency>
41             <groupId>org.projectlombok</groupId>
42             <artifactId>lombok</artifactId>
43             <version>1.18.6</version>
44         </dependency>
45     </dependencies>
46     <build>
47         <plugins>
48             <plugin>
49                 <groupId>org.springframework.boot</groupId>
50                 <artifactId>spring-boot-maven-plugin</artifactId>
51             </plugin>
52         </plugins>
53     </build>
54 </project>

3、程式啟動類

 1 package com.dds.sbswagger;
 2 
 3 import lombok.extern.slf4j.Slf4j;
 4 import org.springframework.boot.SpringApplication;
 5 import org.springframework.boot.autoconfigure.SpringBootApplication;
 6 
 7 /**
 8  * @author dds
 9  */
10 @SpringBootApplication
11 @Slf4j
12 public class SbSwaggerApplication {
13 
14     public static void main(String[] args) {
15         SpringApplication.run(SbSwaggerApplication.class, args);
16         log.info("\n----------------------------------------------------------\n\t" +
17                 "Application demo is running! Access URLs:\n\t" +
18                 "swagger-ui: \thttp://127.0.0.1:8080/swagger-ui.html\n\t" +
19                 "----------------------------------------------------------");
20     }
21 
22 }

4、SwaggerConfig配置類

 1 package com.dds.sbswagger.config;
 2 
 3 import io.swagger.annotations.ApiOperation;
 4 import org.springframework.context.annotation.Bean;
 5 import org.springframework.context.annotation.Configuration;
 6 import springfox.documentation.builders.PathSelectors;
 7 import springfox.documentation.builders.RequestHandlerSelectors;
 8 import springfox.documentation.service.ApiInfo;
 9 import springfox.documentation.service.Contact;
10 import springfox.documentation.spi.DocumentationType;
11 import springfox.documentation.spring.web.plugins.Docket;
12 import springfox.documentation.swagger2.annotations.EnableSwagger2;
13 
14 import java.util.Collections;
15 
16 /**
17  * @author DDS
18  * @date 2019/9/10 13:55
19  */
20 @Configuration
21 @EnableSwagger2
22 public class SwaggerConfig {
23     @Bean
24     public Docket api() {
25         return new Docket(DocumentationType.SWAGGER_2)
26                 .select()
27                 .apis(RequestHandlerSelectors.basePackage("com.dds.sbswagger.controller"))
28                 //加了ApiOperation註解的類,才生成介面文件
29                 .apis(RequestHandlerSelectors.withMethodAnnotation(ApiOperation.class))
30                 .paths(PathSelectors.any())
31                 .build()
32                 .apiInfo(apiInfo());
33     }
34 
35     private ApiInfo apiInfo() {
36         return new ApiInfo(
37                 "Spring Boot專案整合Swagger例項文件",
38                 "我的微信公眾號:大道七哥,歡迎大家關注。",
39                 "API V1.0",
40                 "Terms of service",
41                 new Contact("大道七哥", "https://www.cnblogs.com/jstarseven/", "[email protected]"),
42                 "Apache", "http://www.apache.org/", Collections.emptyList());
43     }
44 }

5、實體類model

 1 package com.dds.sbswagger.model;
 2 
 3 import io.swagger.annotations.ApiModel;
 4 import io.swagger.annotations.ApiModelProperty;
 5 import lombok.Data;
 6 
 7 /**
 8  * @author DDS
 9  * @date 2019/9/10 13:55
10  */
11 @ApiModel("使用者實體")
12 @Data
13 public class User {
14 
15     /**
16      * 使用者Id
17      */
18     @ApiModelProperty("使用者id")
19     private int id;
20 
21     /**
22      * 使用者名稱
23      */
24     @ApiModelProperty(value = "使用者姓名", example = "zhangdan", required = true)
25     private String name;
26 
27     /**
28      * 使用者地址
29      */
30     @ApiModelProperty(value = "使用者地址", example = "北京市海淀區", required = true)
31     private String address;
32 
33     /**
34      * 使用者手機號
35      */
36     @ApiModelProperty(value = "使用者手機號", example = "15689652367", required = true)
37     private String phone;
38 
39     /**
40      * 使用者年齡
41      */
42     @ApiModelProperty(value = "使用者年齡", example = "24", required = true)
43     private Integer age;
44 
45 }

6、介面開發

 1 package com.dds.sbswagger.controller;
 2 
 3 import com.dds.sbswagger.model.User;
 4 import io.swagger.annotations.*;
 5 import org.springframework.web.bind.annotation.*;
 6 
 7 /**
 8  * @author DDS
 9  * @date 2019/9/10 13:55
10  */
11 @RestController
12 @RequestMapping("/user")
13 @Api(tags = "使用者相關介面", description = "提供使用者相關的Rest API")
14 public class UserController {
15 
16     @PostMapping("/add")
17     @ApiOperation(value = "新增使用者介面", notes = "手機號、密碼都是必輸項,年齡隨邊填,但必須是數字")
18     @ApiImplicitParams({
19             @ApiImplicitParam(name = "name", value = "使用者名稱稱", required = true, paramType = "form"),
20             @ApiImplicitParam(name = "address", value = "使用者地址", required = true, paramType = "form"),
21             @ApiImplicitParam(name = "phone", value = "使用者手機號", required = true, paramType = "form"),
22             @ApiImplicitParam(name = "age", value = "使用者年齡", required = true, paramType = "form", dataType = "Integer")
23     })
24     public boolean addUser(@RequestBody User user) {
25         return false;
26     }
27 
28     @ApiOperation("通過id查詢使用者介面")
29     @GetMapping("/find/{id}")
30     public User findById(@PathVariable("id") int id) {
31         return new User();
32     }
33 
34     @ApiOperation("更新使用者資訊介面")
35     @PutMapping("/update")
36     @ApiResponses({
37             @ApiResponse(code = 400, message = "請求引數沒填好"),
38             @ApiResponse(code = 404, message = "請求路徑沒有或頁面跳轉路徑不對"),
39             @ApiResponse(code = 405, message = "未知錯誤")
40     })
41     public boolean update(@RequestBody User user) {
42         return true;
43     }
44 
45     @ApiOperation("刪除使用者介面")
46     @DeleteMapping("/delete/{id}")
47     public boolean delete(@PathVariable("id") int id) {
48         return true;
49     }
50 }

7、swagger介面顯示

  


 -END-

&n