因爲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。具體效果以下圖所示:java
下面來具體介紹,若是在Spring Boot中使用Swagger2。首先,咱們須要一個Spring Boot實現的RESTful API工程。web
在pom.xml
中加入Swagger2的依賴spring
<dependency> <groupId>io.springfox</groupId> <artifactId>springfox-swagger2</artifactId> <version>2.2.2</version> </dependency> <dependency> <groupId>io.springfox</groupId> <artifactId>springfox-swagger-ui</artifactId> <version>2.2.2</version> </dependency>
在Application.java
同級建立Swagger2的配置類Swagger2
。json
@Configuration @EnableSwagger2 public class Swagger2 { @Bean public Docket createRestApi() { return new Docket(DocumentationType.SWAGGER_2) .apiInfo(apiInfo()) .select() .apis(RequestHandlerSelectors.basePackage("com.didispace.web")) .paths(PathSelectors.any()) .build(); } private ApiInfo apiInfo() { return new ApiInfoBuilder() .title("Spring Boot中使用Swagger2構建RESTful APIs") .description("更多Spring Boot相關文章請關注:http://blog.didispace.com/") .termsOfServiceUrl("http://blog.didispace.com/") .contact("程序猿DD") .version("1.0") .build(); } }
如上代碼所示,經過@Configuration
註解,讓Spring來加載該類配置。再經過@EnableSwagger2
註解來啓用Swagger2。再經過createRestApi
函數建立Docket
的Bean以後,apiInfo()
用來建立該Api的基本信息(這些基本信息會展示在文檔頁面中)。select()
函數返回一個ApiSelectorBuilder
實例用來控制哪些接口暴露給Swagger來展示,本例採用指定掃描的包路徑來定義,Swagger會掃描該包下全部Controller定義的API,併產生文檔內容(除了被@ApiIgnore
指定的請求)。api
在完成了上述配置後,其實已經能夠生產文檔內容,可是這樣的文檔主要針對請求自己,而描述主要來源於函數等命名產生,對用戶並不友好,咱們一般須要本身增長一些說明來豐富文檔內容。以下所示,咱們經過@ApiOperation
註解來給API增長說明、經過@ApiImplicitParams
、@ApiImplicitParam
註解來給參數增長說明。數組
@RestController @RequestMapping(value="/users") // 經過這裏配置使下面的映射都在/users下,可去除 public class UserController { static Map<Long, User> users = Collections.synchronizedMap(new HashMap<Long, User>()); @ApiOperation(value="獲取用戶列表", notes="") @RequestMapping(value={""}, method=RequestMethod.GET) public List<User> getUserList() { List<User> r = new ArrayList<User>(users.values()); return r; } @ApiOperation(value="建立用戶", notes="根據User對象建立用戶") @ApiImplicitParam(name = "user", value = "用戶詳細實體user", required = true, dataType = "User") @RequestMapping(value="", method=RequestMethod.POST) public String postUser(@RequestBody User user) { users.put(user.getId(), user); return "success"; } @ApiOperation(value="獲取用戶詳細信息", notes="根據url的id來獲取用戶詳細信息") @ApiImplicitParam(name = "id", value = "用戶ID", required = true, dataType = "Long") @RequestMapping(value="/{id}", method=RequestMethod.GET) public User getUser(@PathVariable Long id) { return users.get(id); } @ApiOperation(value="更新用戶詳細信息", notes="根據url的id來指定更新對象,並根據傳過來的user信息來更新用戶詳細信息") @ApiImplicitParams({ @ApiImplicitParam(name = "id", value = "用戶ID", required = true, dataType = "Long"), @ApiImplicitParam(name = "user", value = "用戶詳細實體user", required = true, dataType = "User") }) @RequestMapping(value="/{id}", method=RequestMethod.PUT) public String putUser(@PathVariable Long id, @RequestBody User user) { User u = users.get(id); u.setName(user.getName()); u.setAge(user.getAge()); users.put(id, u); return "success"; } @ApiOperation(value="刪除用戶", notes="根據url的id來指定刪除對象") @ApiImplicitParam(name = "id", value = "用戶ID", required = true, dataType = "Long") @RequestMapping(value="/{id}", method=RequestMethod.DELETE) public String deleteUser(@PathVariable Long id) { users.remove(id); return "success"; } }
完成上述代碼添加上,啓動Spring Boot程序,訪問:http://localhost:8080/swagger-ui.html。就能看到前文所展現的RESTful API的頁面。咱們能夠再點開具體的API請求,以POST類型的/users請求爲例,可找到上述代碼中咱們配置的Notes信息以及參數user的描述信息,以下圖所示。springboot
在上圖請求的頁面中,咱們看到user的Value是個輸入框?是的,Swagger除了查看接口功能外,還提供了調試測試功能,咱們能夠點擊上圖中右側的Model Schema(黃色區域:它指明瞭User的數據結構),此時Value中就有了user對象的模板,咱們只須要稍適修改,點擊下方「Try it out!」
按鈕,便可完成了一次請求調用!markdown
此時,你也能夠經過幾個GET請求來驗證以前的POST請求是否正確。
相比爲這些接口編寫文檔的工做,咱們增長的配置內容是很是少並且精簡的,對於原有代碼的侵入也在忍受範圍以內。所以,在構建RESTful API的同時,加入swagger來對API文檔進行管理,是個不錯的選擇。
用於類;表示標識這個類是swagger的資源
tags–表示說明
value–也是說明,可使用tags替代
可是tags若是有多個值,會生成多個list
@Api(value="用戶controller",tags={"用戶操做接口"}) @RestController public class UserController { }
效果圖:
用於方法;表示一個http請求的操做
value用於方法描述
notes用於提示內容
tags能夠從新分組(視狀況而用)
用於方法,參數,字段說明;表示對參數的添加元數據(說明或是否必填等)
name–參數名
value–參數說明
required–是否必填
@Api(value="用戶controller",tags={"用戶操做接口"}) @RestController public class UserController { @ApiOperation(value="獲取用戶信息",tags={"獲取用戶信息copy"},notes="注意問題點") @GetMapping("/getUserInfo") public User getUserInfo(@ApiParam(name="id",value="用戶id",required=true) Long id,@ApiParam(name="username",value="用戶名") String username) { // userService可忽略,是業務邏輯 User user = userService.getUserInfo(); return user; } }
效果圖:
用於類 ;表示對類進行說明,用於參數用實體類接收
value–表示對象名
description–描述
均可省略
用於方法,字段; 表示對model屬性的說明或者數據操做更改
value–字段說明
name–重寫屬性名字
dataType–重寫屬性類型
required–是否必填
example–舉例說明
hidden–隱藏
@ApiModel(value="user對象",description="用戶對象user") public class User implements Serializable{ private static final long serialVersionUID = 1L; @ApiModelProperty(value="用戶名",name="username",example="xingguo") private String username; @ApiModelProperty(value="狀態",name="state",required=true) private Integer state; private String password; private String nickName; private Integer isDeleted; @ApiModelProperty(value="id數組",hidden=true) private String[] ids; private List<String> idList; //省略get/set }
@ApiOperation("更改用戶信息") @PostMapping("/updateUserInfo") public int updateUserInfo(@RequestBody @ApiParam(name="用戶對象",value="傳入json格式",required=true) User user){ int num = userService.updateUserInfo(user); return num; }
效果圖:
用於類或者方法上,能夠不被swagger顯示在頁面上
比較簡單, 這裏不作舉例
用於方法
表示單獨的請求參數
用於方法,包含多個 @ApiImplicitParam
name–參數ming
value–參數說明
dataType–數據類型
paramType–參數類型
example–舉例說明
@ApiOperation("查詢測試") @GetMapping("select") //@ApiImplicitParam(name="name",value="用戶名",dataType="String", paramType = "query") @ApiImplicitParams({ @ApiImplicitParam(name="name",value="用戶名",dataType="string", paramType = "query",example="xingguo"), @ApiImplicitParam(name="id",value="用戶id",dataType="long", paramType = "query")}) public void select(){ }
效果圖: