SpirngBoot之整合Swagger2
前言
swagger,中文“拽”的意思。它是一個功能強大的api框架,它的集成非常簡單,不僅提供了在線文檔的查閱,
而且還提供了在線文檔的測試。另外swagger很容易構建restful風格的api。
一、Swagger概述
Swagger是一組圍繞OpenAPI規範構建的開源工具,可幫助設計、構建、記錄和使用REST API。
簡單說下,它的出現就是為了方便進行測試後臺的restful形式的接口,實現動態的更新,當我們在後臺的接口
修改了後,swagger可以實現自動的更新,而不需要認為的維護這個接口進行測試。
二、Swagger常用註解
swagger通過註解表明該接口會生成文檔,包括接口名、請求方法、參數、返回信息的等等。
- @Api:修飾整個類,描述Controller的作用
- @ApiOperation:描述一個類的一個方法,或者說一個接口
- @ApiParam:單個參數描述
- @ApiModel:用對象來接收參數
- @ApiProperty:用對象接收參數時,描述對象的一個字段
- @ApiResponse:HTTP響應其中1個描述
- @ApiResponses:HTTP響應整體描述
- @ApiIgnore:使用該註解忽略這個API
- @ApiError :發生錯誤返回的信息
- @ApiParamImplicitL:一個請求參數
- @ApiParamsImplicit 多個請求參數
三、SpringBoot整合Swagger
3.1 添加依賴
<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>
3.2 添加SwaggerConfiguration
通過@Configuration註解,表明它是一個配置類,@EnableSwagger2開啟swagger2。
apiINfo()配置一些基本的信息。apis()指定掃描的包會生成文檔。
再通過createRestApi函數創建Docket的Bean之後,apiInfo()用來創建該Api的基本信息(這些基本信息會
展現在文檔頁面中)。select()函數返回一個ApiSelectorBuilder實例用來控制哪些接口暴露給Swagger來
展現,本例采用指定掃描的包路徑來定義,Swagger會掃描該包下所有Controller定義的API,並產生文檔內容
(除了被@ApiIgnore指定的請求)。
package com.lance.learn.springbootswagger.configuration;
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.service.Contact;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;
/**
* @author lance(ZYH)
* @function Swagger啟動配置類
* @date 2018-07-09 21:24
*/
@Configuration
@EnableSwagger2
public class SwaggerConfiguration {
/**
* swagger2的配置文件,這裏可以配置swagger2的一些基本的內容,比如掃描的包等等
* @return
*/
@Bean
public Docket createRestfulApi(){
return new Docket(DocumentationType.SWAGGER_2)
.pathMapping("/")
.select()
.apis(RequestHandlerSelectors.basePackage("com.lance.learn.springbootswagger.controller")) //暴露接口地址的包路徑
.paths(PathSelectors.any())
.build();
}
/**
* 構建 api文檔的詳細信息函數,註意這裏的註解引用的是哪個
* @return
*/
private ApiInfo apiInfo(){
return new ApiInfoBuilder()
//頁面標題
.title("Spring Boot 測試使用 Swagger2 構建RESTful API")
//創建人
.contact(new Contact("LanveToBigData", "http://www.cnblogs.com/zhangyinhua/", "[email protected]"))
//版本號
.version("1.0")
//描述
.description("API 描述")
.build();
}
}
3.3 Controller文檔內容
描述主要來源於函數等命名產生,對用戶並不友好,我們通常需要自己增加一些說明來豐富文檔內容。
如下所示,我們通過@ApiOperation註解來給API增加說明、通過@ApiImplicitParams、@ApiImplicitParam
註解來給參數增加說明。
1)實例一
package com.lance.learn.springbootswagger.controller;
import com.lance.learn.springbootswagger.bean.Book;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;
import java.util.*;
/**
* @author lance(ZYH)
* @function
* @date 2018-07-09 21:39
*/
@RestController
@RequestMapping(value = "/bookcurd")
public class BookController {
Map<Long, Book> books = Collections.synchronizedMap(new HashMap<Long, Book>());
@ApiOperation(value="獲取圖書列表", notes="獲取圖書列表")
@RequestMapping(value={""}, method= RequestMethod.GET)
public List<Book> getBook() {
List<Book> book = new ArrayList<>(books.values());
return book;
}
@ApiOperation(value="創建圖書", notes="創建圖書")
@ApiImplicitParam(name = "book", value = "圖書詳細實體", required = true, dataType = "Book")
@RequestMapping(value="", method=RequestMethod.POST)
public String postBook(@RequestBody Book book) {
books.put(book.getId(), book);
return "success";
}
@ApiOperation(value="獲圖書細信息", notes="根據url的id來獲取詳細信息")
@ApiImplicitParam(name = "id", value = "ID", required = true, dataType = "Long",paramType = "path")
@RequestMapping(value="/{id}", method=RequestMethod.GET)
public Book getBook(@PathVariable Long id) {
return books.get(id);
}
@ApiOperation(value="更新信息", notes="根據url的id來指定更新圖書信息")
@ApiImplicitParams({
@ApiImplicitParam(name = "id", value = "圖書ID", required = true, dataType = "Long",paramType = "path"),
@ApiImplicitParam(name = "book", value = "圖書實體book", required = true, dataType = "Book")
})
@RequestMapping(value="/{id}", method= RequestMethod.PUT)
public String putUser(@PathVariable Long id, @RequestBody Book book) {
Book book1 = books.get(id);
book1.setName(book.getName());
book1.setPrice(book.getPrice());
books.put(id, book1);
return "success";
}
@ApiOperation(value="刪除圖書", notes="根據url的id來指定刪除圖書")
@ApiImplicitParam(name = "id", value = "圖書ID", required = true, dataType = "Long",paramType = "path")
@RequestMapping(value="/{id}", method=RequestMethod.DELETE)
public String deleteUser(@PathVariable Long id) {
books.remove(id);
return "success";
}
@ApiIgnore//使用該註解忽略這個API
@RequestMapping(value = "/hi", method = RequestMethod.GET)
public String jsonTest() {
return " hi you!";
}
}
2)實例二
package com.lance.learn.springbootswagger.controller;
import com.lance.learn.springbootswagger.bean.User;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.*;
import java.util.*;
/**
* @author lance(ZYH)
* @function
* @date 2018-07-09 22:00
*/
@RestController
@RequestMapping(value="/users")
public class UserDetailController {
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 = new User();
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";
}
}
3.4 web界面查看
四、項目代碼地址
https://github.com/LanceToBigData/SpringBootLearning/tree/develop/SpringBoot-Swagger
SpirngBoot之整合Swagger2