文章目錄
- 1. Swagger 簡介
- 2. 工程目錄及環境介紹
- 3. SpringBoot 集成 Swagger
- 4. 配置 Swagger 信息
- 5. 配置掃描接口
- 6. 配置是否啓動Swagger
- 7. 配置 API 文檔分組
- 8. 掃描實體類
- 9. 給控制類添加API註解
- 10. Swagger 的測試功能
- 11. Swagger 註解總結
- 11.1 **@Api()**
- 11.2 **@ApiOperation()**
- 11.3 **@ApiModel()**
- 11.4 **@ApiModelProperty**
- 11.5 **@ApiImplicitParams**
- 11.6 **@ApiImplicitParam**
- 11.7 **@ApiParam()**
- 11.8 **@ApiResponses**
- 11.9 **@ApiResponse**
- 11.10 **@ApiIgnore()**
- 11.11 **@Profile({"dev", "test"})**
- 12. 項目源碼
- 13. 參考資料:
1. Swagger 簡介
Swagger是一款RESTFUL接口的文檔在線自動生成+功能測試功能軟件。Swagger是一個規範和完整的框架,用於生成、描述、調用和可視化RESTfu風格的web服務。目標是使客戶端和文件系統作爲服務器一同樣的速度來更新文件的方法,參數和模型緊密集成到服務器。這個解釋簡單點來講就是說,swagger是一款可以根據restful風格生成的接口開發文檔,並且支持做測試的一款中間軟件。
依賴座標
- Springfox Swagger UI
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>2.9.2</version>
</dependency>
- Springfox Swagger2
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>2.9.2</version>
</dependency>
2. 工程目錄及環境介紹
2.1 工程目錄
2.2 環境介紹
- 操作系統:macOS Catalina 10.15.3
- IDEA:IntelliJ IDEA 2019.1 (Ultimate Edition)
- JDK:1.8
- SpringBoot:2.2.6RELEASE
- Swagger UI:2.9.2
- Swagger2:2.9.2
3. SpringBoot 集成 Swagger
3.1 新建 SpringBoot 的 Web 項目
3.2 導入上述2個依賴
<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>
3.3 開啓 Swagger
-
新建一個 SwaggerConfig 類
-
添加 @Configuration:表明這是一個配置類
-
開啓 Swagger2
@Configuration //表明這是一個註解類
@EnableSwagger2 //開啓 Swagger2
public class SwaggerConfig {
}
3.4 測試 Swagger2 是否啓動成功
- 訪問:http://localhost:8089/swagger-ui.html
4. 配置 Swagger 信息
4.1 編寫配置類
package com.kuang.swagger.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.service.Contact;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;
import java.util.ArrayList;
/**
* @author Hedon Wang
* @create 2020-06-23 20:23
*/
@Configuration //表明這是一個註解類
@EnableSwagger2 //開啓 Swagger2
public class SwaggerConfig {
/**
* 配置 Swagger 的 Docket 的 Bean 實例
* @return
*/
@Bean
public Docket docket(){
return new Docket(DocumentationType.SWAGGER_2)
.apiInfo(apiInfo());
}
//配置 Swagger信息=apiInfo
private ApiInfo apiInfo(){
//作者信息
Contact contact = new Contact("Hedon","http://hedon.wang","[email protected]");
return new ApiInfo("Swagger API 文檔", //文檔標題
"這個是一個 Swagger 接口文檔。", //文檔描述
"v1.0", //文檔版本
"http://heon.wang", //隊伍的網站地址
contact, //作者信息
"Apache 2.0", //許可證
"http://www.apache.org/licenses/LICENSE-2.0",//許可證Url
new ArrayList());
}
}
4.2 效果
5. 配置掃描接口
在 SwaggerConfig 中對 Docket 對象繼續進行設定
- select().apis().paths().build()
/**
* 配置 Swagger 的 Docket 的 Bean 實例
* @return
*/
@Bean
public Docket docket(){
return new Docket(DocumentationType.SWAGGER_2)
.apiInfo(apiInfo()) //配置 Swagger ApiInfo 基本信息
.select()
/**
* RequestHandlerSelectors配置要掃描接口的方式
* basePackage:指定要掃描的包=>RequestHandlerSelectors.basePackage("com.kuang.swagger.controller")
* any():掃描全部
* none():全部不掃描
* withClassAnnotation:掃描類上的註解=>RequestHandlerSelectors.withClassAnnotation(RestController.class)
* withMethodAnnotation:掃描方法上的註解=>RequestHandlerSelectors.withMethodAnnotation(GetMapping.class)
*/
.apis(RequestHandlerSelectors.basePackage("com.kuang.swagger.controller"))
/**
* Path:過濾路徑
* ant:指定路徑
* any:過濾全部
* none:全部不過濾
* regex:按照正則表達式來過濾
*/
.paths(PathSelectors.ant("/kuang/**"))
.build(); //工廠模式
}
重新訪問:http://localhost:8089/swagger-ui.html
因爲我們指定了映射路徑爲 /kuang/**,所以目前什麼接口都沒被掃描到
6. 配置是否啓動Swagger
- Docket.enable()
- 這裏我們設置不啓動
6.1 關閉 Swagger
- enable(false)
/**
* 配置 Swagger 的 Docket 的 Bean 實例
* @return
*/
@Bean
public Docket docket(){
return new Docket(DocumentationType.SWAGGER_2)
.apiInfo(apiInfo()) //配置 Swagger ApiInfo 基本信息
.enable(false)
.select()
.apis(RequestHandlerSelectors.basePackage("com.kuang.swagger.controller"))
.paths(PathSelectors.ant("/kuang/**"))
.build(); //工廠模式
}
6.2 測試
- 訪問 http://localhost:8089/swagger-ui.html
7. 配置 API 文檔分組
7.1 配置一個分組
- Docket.groupName()
@Bean
public Docket docket(){
return new Docket(DocumentationType.SWAGGER_2)
.apiInfo(apiInfo()) //配置 Swagger ApiInfo 基本信息
.groupName("Hedon")
.enable(true) //啓動
.select()
.apis(RequestHandlerSelectors.basePackage("com.kuang.swagger.controller"))
.paths(PathSelectors.ant("/kuang/**"))
.build(); //工廠模式
}
- 訪問: http://localhost:8089/swagger-ui.html
7.2 配置多個分組
- 建立多個 Docket 實例對象
@Bean
public Docket docket1(){
return new Docket(DocumentationType.SWAGGER_2)
.groupName("A");
}
@Bean
public Docket docket2(){
return new Docket(DocumentationType.SWAGGER_2)
.groupName("B");
}
@Bean
public Docket docket3(){
return new Docket(DocumentationType.SWAGGER_2)
.groupName("C");
}
- 訪問: http://localhost:8089/swagger-ui.html
8. 掃描實體類
8.1 新建一個實體類 User
8.2 Controller 中新加一個方法,返回一個 User 對象
- 只要我們的接口中,返回值存在實體類,它就會被掃描到 Swagger 中
@PostMapping("/user")
public User user(){
return new User("heodn","12345");
}
- 訪問: http://localhost:8089/swagger-ui.html
8.3 給實體類添加 API 註釋
- @ApiModel
@ApiModel("這是User實體類")
public class User {
8.4 給實體類的屬性添加 API 註釋
- @ApiModelProperty
@ApiModelProperty("用戶名")
public String username;
@ApiModelProperty("密碼")
public String password;
9. 給控制類添加API註解
9.1 接口添加說明註解
- @ApiOpeartion(value=“接口名”,httpMethod=“請求方式”,notes=“詳細說明”)
@GetMapping("/hello")
@ApiOperation(value = "Hello接口",httpMethod = "GET",notes = "這是Hello接口的詳細說明。")
public String hello(){
return "hello springboot";
}
9.2 添加接口參數說明註解
- @ApiImplicitParams 包含多個屬性
- @ApiImplicitParam
- name:屬性名
- value:屬性值
- defaultValue:默認值
- paramType:表示參數放在哪個地方
-
header–>請求參數的獲取:@RequestHeader(代碼中接收註解)
-
query–>請求參數的獲取:@RequestParam(代碼中接收註解)
-
path(用於restful接口)–>請求參數的獲取:@PathVariable(代碼中接收註解)
-
body–>請求參數的獲取:@RequestBody(代碼中接收註解)
-
form(不常用,form.serilize())
-
- dataType:參數類型
- required:是否必須
@GetMapping("/hello")
@ApiOperation(value = "Hello接口",httpMethod = "GET",notes = "這是Hello接口的詳細說明。")
@ApiImplicitParams({
@ApiImplicitParam(name = "username",value = "用戶名",defaultValue = "hedon",paramType = "query",dataType="String",required = true),
@ApiImplicitParam(name = "password",value = "密碼",defaultValue = "hedonpassword",paramType = "query",dataType="String",required = true)
})
public String hello(String username,String password){
return "hello,your username = "+username +" and your password = "+password;
}
10. Swagger 的測試功能
10.1 點擊”try it out“
10.2 輸入參數
10.3 執行查看結果
11. Swagger 註解總結
11.1 @Api()
-
用在請求的類上,表示對類的說明,也代表了這個類是swagger2的資源。
-
參數:
tags:說明該類的作用,參數是個數組,可以填多個。
value=“該參數沒什麼意義,在UI界面上不顯示,所以不用配置”
description = “用戶基本信息操作”
11.2 @ApiOperation()
-
用於方法,表示一個http請求訪問該方法的操作。
-
參數:
value=“方法的用途和作用”
notes=“方法的注意事項和備註”
tags:說明該方法的作用,參數是個數組,可以填多個。
格式:tags={“作用1”,“作用2”}
(在這裏建議不使用這個參數,會使界面看上去有點亂,前兩個常用)
11.3 @ApiModel()
-
用於響應實體類上,用於說明實體作用。
-
參數:
description=“描述實體的作用”
11.4 @ApiModelProperty
-
用在屬性上,描述實體類的屬性
-
參數:
value=“用戶名” 描述參數的意義
name=“name” 參數的變量名
required=true 參數是否必選
11.5 @ApiImplicitParams
- 用在請求的方法上,包含多@ApiImplicitParam
11.6 @ApiImplicitParam
-
用於方法,表示單獨的請求參數。
-
參數:
name=“參數ming”
value=“參數說明”
dataType=“數據類型”
paramType=“query” 表示參數放在哪裏
-header–>請求參數的獲取:@RequestHeader(代碼中接收註解) -query–>請求參數的獲取:@RequestParam(代碼中接收註解)
-path(用於restful接口)–>請求參數的獲取:@PathVariable(代碼中接收註解)
-body–>請求參數的獲取:@RequestBody(代碼中接收註解)
-form(不常用,form.serilize())
defaultValue=“參數的默認值”
required=“true” 表示參數是否必須傳
11.7 @ApiParam()
-
用於方法,參數,字段說明 表示對參數的要求和說明。
-
參數:
name=“參數名稱”
value=“參數的簡要說明”
defaultValue=“參數默認值”
required=“true” 表示屬性是否必填,默認爲false
11.8 @ApiResponses
- 用於請求的方法上,根據響應碼錶示不同響應。
- 一個@ApiResponses包含多個@ApiResponse。
11.9 @ApiResponse
-
用在請求的方法上,表示不同的響應。
-
參數:
code=“404” 表示響應碼(int型),可自定義
message=“狀態碼對應的響應信息”
11.10 @ApiIgnore()
- 用於類或者方法上,不被顯示在頁面上。
11.11 @Profile({“dev”, “test”})
- 用於配置類上,表示只對開發和測試環境有用。
12. 項目源碼
12.1 SwaggerDemoApplication.java
package com.kuang.swagger;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import springfox.documentation.swagger2.annotations.EnableSwagger2;
@SpringBootApplication
@EnableSwagger2
public class SwaggerDemoApplication {
public static void main(String[] args) {
SpringApplication.run(SwaggerDemoApplication.class, args);
}
}
12.2 HelloController.java
package com.kuang.swagger.controller;
import com.kuang.swagger.pojo.User;
import io.swagger.annotations.*;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;
/**
* @author Hedon Wang
* @create 2020-06-23 20:19
*/
@RestController
public class HelloController {
@GetMapping("/hello")
@ApiOperation(value = "Hello接口",httpMethod = "GET",notes = "這是Hello接口的詳細說明。")
@ApiImplicitParams({
@ApiImplicitParam(name = "username",value = "用戶名",defaultValue = "hedon",paramType = "query",dataType="String",required = true),
@ApiImplicitParam(name = "password",value = "密碼",defaultValue = "hedonpassword",paramType = "query",dataType="String",required = true)
})
public String hello(String username,String password){
return "hello,your username = "+username +" and your password = "+password;
}
//只要我們的接口中,返回值存在實體類,它就會被掃描到 Swagger 中
@PostMapping("/user")
public User user(){
return new User("heodn","12345");
}
}
12.3 SwaggerConfig.java
package com.kuang.swagger.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Profile;
import org.springframework.core.env.Environment;
import org.springframework.core.env.Profiles;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.service.Contact;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;
import java.util.ArrayList;
/**
* @author Hedon Wang
* @create 2020-06-23 20:23
*/
@Configuration //表明這是一個註解類
@EnableSwagger2 //開啓 Swagger2
public class SwaggerConfig {
@Bean
public Docket docket1(){
return new Docket(DocumentationType.SWAGGER_2)
.groupName("A");
}
@Bean
public Docket docket2(){
return new Docket(DocumentationType.SWAGGER_2)
.groupName("B");
}
@Bean
public Docket docket3(){
return new Docket(DocumentationType.SWAGGER_2)
.groupName("C");
}
/**
* 配置 Swagger 的 Docket 的 Bean 實例
* @return
*/
@Bean
public Docket docket(){
return new Docket(DocumentationType.SWAGGER_2)
.apiInfo(apiInfo()) //配置 Swagger ApiInfo 基本信息
.groupName("Hedon")
.enable(true) //啓動
.select()
/**
* RequestHandlerSelectors配置要掃描接口的方式
* basePackage:指定要掃描的包=>RequestHandlerSelectors.basePackage("com.kuang.swagger.controller")
* any():掃描全部
* none():全部不掃描
* withClassAnnotation:掃描類上的註解=>RequestHandlerSelectors.withClassAnnotation(RestController.class)
* withMethodAnnotation:掃描方法上的註解=>RequestHandlerSelectors.withMethodAnnotation(GetMapping.class)
*/
.apis(RequestHandlerSelectors.basePackage("com.kuang.swagger.controller"))
/**
* Path:過濾路徑
* ant:指定路徑
* any:過濾全部
* none:全部不過濾
* regex:按照正則表達式來過濾
*/
.paths(PathSelectors.ant("/kuang/**"))
.build(); //工廠模式
}
//配置 Swagger信息=apiInfo
private ApiInfo apiInfo(){
//作者信息
Contact contact = new Contact("Hedon","http://hedon.wang","[email protected]");
return new ApiInfo("Swagger API 文檔", //文檔標題
"這個是一個 Swagger 接口文檔。", //文檔描述
"v1.0", //文檔版本
"http://heon.wang", //隊伍的網站地址
contact, //作者信息
"Apache 2.0", //許可證
"http://www.apache.org/licenses/LICENSE-2.0",//許可證Url
new ArrayList());
}
}
12.4 User.java
package com.kuang.swagger.pojo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
/**
* @author Hedon Wang
* @create 2020-06-23 21:27
*/
@ApiModel("這是User實體類")
public class User {
@ApiModelProperty("用戶名")
public String username;
@ApiModelProperty("密碼")
public String password;
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public User() {
}
public User(String username, String password) {
this.username = username;
this.password = password;
}
@Override
public String toString() {
return "User{" +
"username='" + username + '\'' +
", password='" + password + '\'' +
'}';
}
}
13. 參考資料:
bilibili視頻:《狂神說:一小時掌握 Swagger 技術》
知乎:https://zhuanlan.zhihu.com/p/49996147