因爲Spring Boot可以快速開發、便捷部署等特性,相信有很大一部分Spring Boot的用戶會用來構建RESTful API。而咱們構建RESTful API的目的一般都是因爲多終端的緣由,這些終端會共用不少底層業務邏輯,所以咱們會抽象出這樣一層來同時服務於多個移動端或者Web前端。html
這樣一來,咱們的RESTful API就有可能要面對多個開發人員或多個開發團隊:IOS開發、Android開發或是Web開發等。爲了減小與其餘團隊平時開發期間的頻繁溝通成本,傳統作法咱們會建立一份RESTful API文檔來記錄全部接口細節,然而這樣的作法有如下幾個問題:前端
爲了解決上面這樣的問題,本文將介紹RESTful API的重磅好夥伴Swagger2,它能夠輕鬆的整合到Spring Boot中,並與Spring MVC程序配合組織出強大RESTful API文檔。它既能夠減小咱們建立文檔的工做量,同時說明內容又整合入實現代碼中,讓維護文檔和修改代碼整合爲一體,可讓咱們在修改代碼邏輯的同時方便的修改文檔說明。另外Swagger2也提供了強大的頁面測試功能來調試每一個RESTful API。具體效果以下圖所示:git
在使用Swagger2前咱們須要有一個RESTful API的項目. Spring-Boot建立RESTful API項目很是的方便和快速,這裏再也不介紹如何建立github
在pom.xml文件中加入如下依賴:web
<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>
經過@Configuration
註解,代表它是一個配置類,@EnableSwagger2
註解開啓swagger2。apiInfo() 方法配置一些基本的信息。createRestApi() 方法指定掃描的包會生成文檔,默認是顯示全部接口,能夠用@ApiIgnore
註解標識該接口不顯示。spring
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。api
再經過createRestApi
函數建立Docket
的Bean以後,apiInfo()
用來建立該Api的基本信息(這些基本信息會展示在文檔頁面中)。select()
函數返回一個ApiSelectorBuilder
實例用來控制哪些接口暴露給Swagger來展示,本例採用指定掃描的包路徑來定義,Swagger會掃描該包下全部Controller定義的API,併產生文檔內容(除了被@ApiIgnore
指定的請求)。數據結構
在完成了上述配置後,其實已經能夠生產文檔內容,可是這樣的文檔主要針對請求自己,而描述主要來源於函數等命名產生,對用戶並不友好,咱們一般須要本身增長一些說明來豐富文檔內容。以下所示,咱們經過@ApiOperation
註解來給API增長說明、經過@ApiImplicitParams
、@ApiImplicitParam
註解來給參數增長說明。app
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的描述信息,以下圖所示。函數
在上圖請求的頁面中,咱們看到user的Value是個輸入框?是的,Swagger除了查看接口功能外,還提供了調試測試功能,咱們能夠點擊上圖中右側的Model Schema(黃色區域:它指明瞭User的數據結構),此時Value中就有了user對象的模板,咱們只須要稍適修改,點擊下方「Try it out!」
按鈕,便可完成了一次請求調用!
此時,你也能夠經過幾個GET請求來驗證以前的POST請求是否正確。
相比爲這些接口編寫文檔的工做,咱們增長的配置內容是很是少並且精簡的,對於原有代碼的侵入也在忍受範圍以內。所以,在構建RESTful API的同時,加入swagger來對API文檔進行管理,是個不錯的選擇。
@ApiOperation
:用在方法上,說明方法的做用
@ApiImplicitParams
:用在方法上包含一組參數說明
@ApiImplicitParam
:用在@apiimplicitparams註解中,指定一個請求參數的各個方面
@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>