綜合概述
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://gitee.com/liuge1988/spring-boot-demo.git
作者:朝雨憶輕塵
出處:https://www.cnblogs.com/xifengxiaoma/
版權所有,歡迎轉載,轉載請注明原文作者及出處。
