由於Spring Boot能夠快速開發、便捷部署等特性,相信有很大一部分Spring Boot的用戶會用來構建RESTful API。而我們構建RESTful API的目的通常都是由於多終端的原因,這些終端會共用很多底層業務邏輯,因此我們會抽象出這樣一層來同時服務於多個移動端或者Web前端。
這樣一來,我們的RESTful API就有可能要面對多個開發人員或多個開發團隊:IOS開發、Android開發或是Web開發等。為了減少與其他團隊平時開發期間的頻繁溝通成本,傳統做法我們會創建一份RESTful API文檔來記錄所有接口細節,然而這樣的做法有以下幾個問題:
- 由於接口眾多,並且細節復雜(需要考慮不同的HTTP請求類型、HTTP頭部信息、HTTP請求內容等),高質量地創建這份文檔本身就是件非常吃力的事,下游的抱怨聲不絕於耳。
- 隨着時間推移,不斷修改接口實現的時候都必須同步修改接口文檔,而文檔與代碼又處於兩個不同的媒介,除非有嚴格的管理機制,不然很容易導致不一致現象。
為了解決上面這樣的問題,本文將介紹RESTful API的重磅好伙伴Swagger2,它可以輕松的整合到Spring Boot中,並與Spring MVC程序配合組織出強大RESTful API文檔。它既可以減少我們創建文檔的工作量,同時說明內容又整合入實現代碼中,讓維護文檔和修改代碼整合為一體,可以讓我們在修改代碼邏輯的同時方便的修改文檔說明。另外Swagger2也提供了強大的頁面測試功能來調試每個RESTful API。具體效果如下圖所示:
構建RESTful API
在使用Swagger2前我們需要有一個RESTful API的項目. Spring-Boot創建RESTful API項目非常的方便和快速,這里不再介紹如何創建
添加Swagger2依賴
在pom.xml文件中加入以下依賴:
<dependency> <groupId>io.springfox</groupId> <artifactId>springfox-swagger2</artifactId> <version>2.7.0</version> </dependency> <dependency> <groupId>io.springfox</groupId> <artifactId>springfox-swagger-ui</artifactId> <version>2.7.0</version> </dependency>
創建Swagger2的Java配置類
通過@Configuration
注解,表明它是一個配置類,@EnableSwagger2
注解開啟swagger2。apiInfo() 方法配置一些基本的信息。createRestApi() 方法指定掃描的包會生成文檔,默認是顯示所有接口,可以用@ApiIgnore
注解標識該接口不顯示。
1 @Configuration 2 @EnableSwagger2 3 public class Swagger2 { 4 5 @Bean 6 public Docket createRestApi() { 7 return new Docket(DocumentationType.SWAGGER_2) 8 .apiInfo(apiInfo()) 9 .select() 10 .apis(RequestHandlerSelectors.basePackage("com.didispace.web")) 11 .paths(PathSelectors.any()) 12 .build(); 13 } 14 15 private ApiInfo apiInfo() { 16 return new ApiInfoBuilder() 17 .title("Spring Boot中使用Swagger2構建RESTful APIs") 18 .description("更多Spring Boot相關文章請關注") 19 .termsOfServiceUrl("http://blog.didispace.com/") 20 .contact("程序猿") 21 .version("1.0") 22 .build(); 23 } 24 25 }
如上代碼所示,通過@Configuration
注解,讓Spring來加載該類配置。再通過@EnableSwagger2
注解來啟用Swagger2。
再通過createRestApi
函數創建Docket
的Bean之后,apiInfo()
用來創建該Api的基本信息(這些基本信息會展現在文檔頁面中)。select()
函數返回一個ApiSelectorBuilder
實例用來控制哪些接口暴露給Swagger來展現,本例采用指定掃描的包路徑來定義,Swagger會掃描該包下所有Controller定義的API,並產生文檔內容(除了被@ApiIgnore
指定的請求)。
添加文檔內容
在完成了上述配置后,其實已經可以生產文檔內容,但是這樣的文檔主要針對請求本身,而描述主要來源於函數等命名產生,對用戶並不友好,我們通常需要自己增加一些說明來豐富文檔內容。如下所示,我們通過@ApiOperation
注解來給API增加說明、通過@ApiImplicitParams
、@ApiImplicitParam
注解來給參數增加說明。
1 @RestController 2 @RequestMapping(value="/users") // 通過這里配置使下面的映射都在/users下,可去除 3 public class UserController { 4 5 static Map<Long, User> users = Collections.synchronizedMap(new HashMap<Long, User>()); 6 7 @ApiOperation(value="獲取用戶列表", notes="") 8 @RequestMapping(value={""}, method=RequestMethod.GET) 9 public List<User> getUserList() { 10 List<User> r = new ArrayList<User>(users.values()); 11 return r; 12 } 13 14 @ApiOperation(value="創建用戶", notes="根據User對象創建用戶") 15 @ApiImplicitParam(name = "user", value = "用戶詳細實體user", required = true, dataType = "User") 16 @RequestMapping(value="", method=RequestMethod.POST) 17 public String postUser(@RequestBody User user) { 18 users.put(user.getId(), user); 19 return "success"; 20 } 21 22 @ApiOperation(value="獲取用戶詳細信息", notes="根據url的id來獲取用戶詳細信息") 23 @ApiImplicitParam(name = "id", value = "用戶ID", required = true, dataType = "Long") 24 @RequestMapping(value="/{id}", method=RequestMethod.GET) 25 public User getUser(@PathVariable Long id) { 26 return users.get(id); 27 } 28 29 @ApiOperation(value="更新用戶詳細信息", notes="根據url的id來指定更新對象,並根據傳過來的user信息來更新用戶詳細信息") 30 @ApiImplicitParams({ 31 @ApiImplicitParam(name = "id", value = "用戶ID", required = true, dataType = "Long"), 32 @ApiImplicitParam(name = "user", value = "用戶詳細實體user", required = true, dataType = "User") 33 }) 34 @RequestMapping(value="/{id}", method=RequestMethod.PUT) 35 public String putUser(@PathVariable Long id, @RequestBody User user) { 36 User u = users.get(id); 37 u.setName(user.getName()); 38 u.setAge(user.getAge()); 39 users.put(id, u); 40 return "success"; 41 } 42 43 @ApiOperation(value="刪除用戶", notes="根據url的id來指定刪除對象") 44 @ApiImplicitParam(name = "id", value = "用戶ID", required = true, dataType = "Long") 45 @RequestMapping(value="/{id}", method=RequestMethod.DELETE) 46 public String deleteUser(@PathVariable Long id) { 47 users.remove(id); 48 return "success"; 49 } 50 51 }
完成上述代碼添加上,啟動Spring Boot程序,訪問:http://localhost:8080/swagger-ui.html
。就能看到前文所展示的RESTful API的頁面。我們可以再點開具體的API請求,以POST類型的/users請求為例,可找到上述代碼中我們配置的Notes信息以及參數user的描述信息,如下圖所示。
API文檔訪問與調試
在上圖請求的頁面中,我們看到user的Value是個輸入框?是的,Swagger除了查看接口功能外,還提供了調試測試功能,我們可以點擊上圖中右側的Model Schema(黃色區域:它指明了User的數據結構),此時Value中就有了user對象的模板,我們只需要稍適修改,點擊下方“Try it out!”
按鈕,即可完成了一次請求調用!
此時,你也可以通過幾個GET請求來驗證之前的POST請求是否正確。
相比為這些接口編寫文檔的工作,我們增加的配置內容是非常少而且精簡的,對於原有代碼的侵入也在忍受范圍之內。因此,在構建RESTful API的同時,加入swagger來對API文檔進行管理,是個不錯的選擇。
Annotation使用詳解
@ApiOperation
:用在方法上,說明方法的作用
- value: 表示接口名稱
- notes: 表示接口詳細描述
@ApiImplicitParams
:用在方法上包含一組參數說明
@ApiImplicitParam
:用在@apiimplicitparams注解中,指定一個請求參數的各個方面
- paramType:參數位置
- header 對應注解:@requestheader
- query 對應注解:@requestparam
- path 對應注解: @pathvariable
- body 對應注解: @requestbody
- name:參數名
- dataType:參數類型
- required:參數是否必須傳
- value:參數的描述
- defaultValue:參數的默認值
@ApiResponses
:用於表示一組響應
@ApiResponse
:用在@apiresponses中,一般用於表達一個錯誤的響應信息
-
code:狀態碼
-
message:返回自定義信息
-
response:拋出異常的類
@ApiModel
描述一個Model的信息(這種一般用在post創建的時候,使用@RequestBody這樣的場景,請求參數無法使用@ApiImplicitParam注解進行描述的時候)
@ApiModel(value = "用戶實體類")
@ApiModelProperty
描述一個model的屬性
@ApiModelProperty(value = "登錄用戶")
附:
1 <dependency> 2 <groupId>io.springfox</groupId> 3 <artifactId>springfox-swagger2</artifactId> 4 <version>2.9.2</version> 5 <!-- 解決 io.swagger.models.parameters.AbstractSerializableParameter.getExample @ApiModelProperty example 必須為數字的問題 --> 6 <exclusions> 7 <exclusion> 8 <groupId>io.swagger</groupId> 9 <artifactId>swagger-annotations</artifactId> 10 </exclusion> 11 <exclusion> 12 <groupId>io.swagger</groupId> 13 <artifactId>swagger-models</artifactId> 14 </exclusion> 15 </exclusions> 16 </dependency> 17 <dependency> 18 <groupId>io.swagger</groupId> 19 <artifactId>swagger-annotations</artifactId> 20 <version>1.5.21</version> 21 </dependency> 22 <dependency> 23 <groupId>io.swagger</groupId> 24 <artifactId>swagger-models</artifactId> 25 <version>1.5.21</version> 26 </dependency> 27 <dependency> 28 <groupId>io.springfox</groupId> 29 <artifactId>springfox-swagger-ui</artifactId> 30 <version>2.9.2</version> 31 </dependency>
參考資料:https://blog.csdn.net/itguangit/article/details/78978296