Spring Boot:整合Swagger文件
綜合概述
spring-boot作為當前最為流行的Java web開發腳手架,越來越多的開發者選擇用其來構建企業級的RESTFul API介面。這些介面不但會服務於傳統的web端(b/s),也會服務於移動端。在實際開發過程中,這些介面還要提供給開發測試進行相關的白盒測試,那麼勢必存在如何在多人協作中共享和及時更新API開發介面文件的問題。
假如你已經對傳統的wiki文件共享方式所帶來的弊端深惡痛絕,那麼嘗試一下Swagger2 方式,一定會讓你有不一樣的開發體驗。
使用 Swagger 整合文件具有以下幾個優勢:
- 功能豐富 :支援多種註解,自動生成介面文件介面,支援在介面測試API介面功能;
- 及時更新 :開發過程中花一點寫註釋的時間,就可以及時的更新API文件,省心省力;
- 整合簡單 :通過新增pom依賴和簡單配置,內嵌於應用中就可同時釋出API介面文件介面,不需要部署獨立服務。
實現案例
接下來,我們就通過Spring Boot 來整合Swagger實現線上API文件的功能。
生成專案模板
為方便我們初始化專案,Spring Boot給我們提供一個專案模板生成網站。
1. 開啟瀏覽器,訪問:https://start.spring.io/
2. 根據頁面提示,選擇構建工具,開發語言,專案資訊等。
3. 點選 Generate the project,生成專案模板,生成之後會將壓縮包下載到本地。
4. 使用IDE匯入專案,我這裡使用Eclipse,通過匯入Maven專案的方式匯入。
新增相關依賴
新增 Maven 相關依賴,這裡需要新增上WEB和SWAGGER依賴。
WEB依賴
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency>
swagger依賴,這裡選擇 2.9.2 版本。
<!-- swagger --> <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>
新增配置類
新增一個swagger 配置類,在工程下新建 config 包並新增一個 SwaggerConfig 配置類。
SwaggerConfig.java
import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import springfox.documentation.builders.ApiInfoBuilder; import springfox.documentation.builders.PathSelectors; import springfox.documentation.builders.RequestHandlerSelectors; import springfox.documentation.service.ApiInfo; import springfox.documentation.spi.DocumentationType; import springfox.documentation.spring.web.plugins.Docket; import springfox.documentation.swagger2.annotations.EnableSwagger2; @Configuration @EnableSwagger2 public class SwaggerConfig { @Bean public Docket createRestApi(){ return new Docket(DocumentationType.SWAGGER_2).apiInfo(apiInfo()) .select() .apis(RequestHandlerSelectors.any()) .paths(PathSelectors.any()).build(); } private ApiInfo apiInfo(){ return new ApiInfoBuilder() .title("Kitty API Doc") .description("This is a restful api document of Kitty.") .version("1.0") .build(); } }
新增控制器
新增一個控制器,在工程下新建 controller包並新增一個 HelloController控制器。
HelloController.java
package com.louis.springboot.demo.controller; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; import io.swagger.annotations.Api; import io.swagger.annotations.ApiOperation; import io.swagger.annotations.ApiParam; /* 類註解 */ @Api(value = "desc of class") @RestController public class HelloController { /* 方法註解 */ @ApiOperation(value = "desc of method", notes = "") @GetMapping(value="/hello") public Object hello( /* 引數註解 */ @ApiParam(value = "desc of param" , required=true ) @RequestParam String name) { return "Hello " + name + "!"; } }
編譯執行測試
1. 右鍵專案 -> Run as -> Maven install,開始執行Maven構建,第一次會下載Maven依賴,可能需要點時間,如果出現如下資訊,就說明專案編譯打包成功了。
2. 右鍵檔案 DemoApplication.java -> Run as -> Java Application,開始啟動應用,當出現如下資訊的時候,就說明應用啟動成功了,預設啟動埠是8080。
3. 開啟瀏覽器,訪問:http://localhost:8080/swagger-ui.html,進入swagger介面文件介面。
4. 展開hello-controller的hello介面,輸入引數並點選執行,就可以看到介面測試結果了。
常用註解說明
swagger 通過註解介面生成文件,包括介面名,請求方法,引數,返回資訊等。
@Api: 修飾整個類,用於controller類上
@ApiOperation: 描述一個介面,使用者controller方法上
@ApiParam: 單個引數描述
@ApiModel: 用來物件接收引數,即返回物件
@ApiModelProperty: 物件接收引數時,描述物件的欄位
@ApiResponse: Http響應其中的描述,在ApiResonse中
@ApiResponses: Http響應所有的描述,用在
@ApiIgnore: 忽略這個API
@ApiError: 發生錯誤的返回資訊
@ApiImplicitParam: 一個請求引數
@ApiImplicitParam: 多個請求引數
更多使用說明,參考 Swagger 使用手冊。
新增請求引數
在很多時候,我們需要在呼叫我們每一個介面的時候都攜帶上一些通用引數,比如採取token驗證邏輯的往往在介面請求時需要把token也一起傳入後臺,接下來,我們就來講解一下如何給Swagger新增固定的請求引數。
修改SwaggerConfig配置類,替換成如下內容,利用ParameterBuilder構成請求引數。
SwaggerConfig.java
@Configuration @EnableSwagger2 public class SwaggerConfig { @Bean public Docket createRestApi(){ // 新增請求引數,我們這裡把token作為請求頭部引數傳入後端 ParameterBuilder parameterBuilder = new ParameterBuilder(); List<Parameter> parameters = new ArrayList<Parameter>(); parameterBuilder.name("token").description("令牌") .modelRef(new ModelRef("string")).parameterType("header").required(false).build(); parameters.add(parameterBuilder.build()); return new Docket(DocumentationType.SWAGGER_2).apiInfo(apiInfo()).select() .apis(RequestHandlerSelectors.any()).paths(PathSelectors.any()) .build().globalOperationParameters(parameters); // return new Docket(DocumentationType.SWAGGER_2).apiInfo(apiInfo()) // .select() // .apis(RequestHandlerSelectors.any()) // .paths(PathSelectors.any()).build(); } private ApiInfo apiInfo(){ return new ApiInfoBuilder() .title("Swagger API Doc") .description("This is a restful api document of Swagger.") .version("1.0") .build(); } }
完成之後重新啟動應用,再次檢視hello介面,可以看到已經支援傳送token請求引數了。
胡言亂語
前後端分離架構好,不用程式碼網頁一起搞。
你寫你頁面,我寫我介面,中間交由Swagger來接手。
文件風格簡潔而優雅,介面測試簡單又方便。
參考資料
官方網站:https://swagger.io/
使用手冊:https://gumutianqi1.gitbooks.io/specification-doc/content/tools-doc/spring-boot-swagger2-guide.html
Maven倉庫:https://mvnrepository.com/artifact/io.springfox/springfox-swagger-ui
作者:朝雨憶輕塵
出處:https://www.cnblogs.com/xifengxiaoma/
版權所有,歡迎轉載,轉載請註明原文作者及出處。
作者:朝雨憶輕塵
出處:https://www.cnblogs.com/xifengxiaoma/
版權所有,歡迎轉載,轉載請註明原文作者及出處。