Lison <[email protected]>
, v1.0.0, 2019.10.13
SpringBoot系統搭建集成-006-集成swagger2
簡介和配置
Swagger2是一款RESTFUL接口的文檔在線自動生成和功能測試功能軟件
Swagger 是一個規範和完整的框架,用於生成、描述、調用和可視化 RESTful 風格的 Web 服務。總體目標是使客戶端和文件系統作爲服務器以同樣的速度來更新。文件的方法,參數和模型緊密集成到服務器端的代碼,允許API來始終保持同步。Swagger 讓部署管理和使用功能強大的API從未如此簡單 。
修改pom.添加依賴:
<io.springfox.swagger.version>2.8.0</io.springfox.swagger.version>
<!--swagger-->
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>${io.springfox.swagger.version}</version>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>${io.springfox.swagger.version}</version>
</dependency>
<!-- <dependency>
<groupId>com.github.xiaoymin</groupId>
<artifactId>swagger-bootstrap-ui</artifactId>
<version>1.9.0</version>
</dependency>-->
添加配置類
/**
* @author : Lison
* @Date: 2019/10/16 15:08
* @Description:
*/
@Configuration
@EnableSwagger2
public class SwaggerConfig {
@Bean
public Docket docket(){
return new Docket(DocumentationType.SWAGGER_2)
.useDefaultResponseMessages(false)
.select()
.apis(RequestHandlerSelectors.basePackage("com.github.cundream"))
.paths(PathSelectors.regex("(?!auth).*$"))
.build()
.securityContexts(securityContexts());
}
private List<SecurityContext> securityContexts() {
return Lists.newArrayList(
SecurityContext.builder()
.securityReferences(defaultAuth())
.forPaths(PathSelectors.regex("^(?!auth).*$"))
.build()
);
}
private List<SecurityReference> defaultAuth() {
AuthorizationScope authorizationScope = new AuthorizationScope("global", "accessEverything");
AuthorizationScope[] authorizationScopes = new AuthorizationScope[]{authorizationScope};
SecurityReference securityReference = new SecurityReference("X-Authorization", authorizationScopes);
return Lists.newArrayList(securityReference);
}
private ApiInfo getApiInfo(){
return new ApiInfoBuilder()
.title("API接口文檔")
.description("swagger2 api")
.termsOfServiceUrl("http://localhost/swagger-ui.html")
.version("1.0")
.contact(new Contact("Lison", "http://localhost/swagger-ui.html", "[email protected]"))
.build();
}
}
.apis(RequestHandlerSelectors.basePackage("com.github.cundream"))
會將包下的所有被@Api標記的類帶有@RequestMapping或者XxxMapping都會給暴露給swagger
.apis(RequestHandlerSelectors.withMethodAnnotation(ApiOperation.class))
只有在類上使用@Api註解標註並且在方法上使用@ApiOperation註解纔會暴露給swagger,這種方式沒有包名的限制,可以將需要暴露的接口分散到各個包裏,只要類上有@Api註解方法上有@ApiOperation註解就能暴露出來,如果不想暴露出來就不用使用這兩個註解
Swagger 各註解說明
@RestController
@RequestMapping("/user")
@Api(value = "UserController", tags = "user", description = "User相關接口")
public class UserController
@Api用來標識Class
@ApiOperation(value = "獲取用戶信息", notes = "獲取用戶信息")
@ApiResponses({
@ApiResponse(code = 200, message = "success"),
@ApiResponse(code = 10001, message = "secret_key與token不符合"),
@ApiResponse(code = 10002, message = "獲取用戶信息錯誤", response = Exception.class)
})
@PostMapping("/getUserinfo")
public String getUsesrInfo(@ApiParam(name = "secret_key", value = "祕鑰", required = true) @RequestParam String secret_key,
@ApiParam(name = "token", value = "token", required = true) @RequestParam String token,
@ApiParam(name = "type", value = "用戶類型", required = true) @RequestParam String type){
return "{'type': " + type + ", 'url': 'rtmp://localhost/user', 'urlHD': 'rtmp://localhost/hd/user'}";
}
@ApiOperation(value = “接口方法的名稱”, notes = “備註說明”)
@ApiParam(name = “參數名稱”, value = “備註說明”, required = 是否必須):標註在方法的參數上 用於描述參數的名稱、備註、是否必須等信息
@ApiImplicitParams: 用於包含多個@ApiImplicitParam
@ApiResponse(code = 0, message = “success”),
- code:響應碼,例如400
- message:信息,一般是對code的描述
- response:拋出異常的類
@ApiOperation(value = "修改用戶信息", notes = "修改用戶信息")
@ApiImplicitParams({
@ApiImplicitParam(dataTypeClass = String.class, paramType = "header", name = "id", value = "id標識", required = true),
@ApiImplicitParam(dataTypeClass = String.class, paramType = "query", name = "userName", value = "登陸名", required = true),
@ApiImplicitParam(dataTypeClass = String.class, paramType = "path", name = "passWord", value = "密碼", required = true),
@ApiImplicitParam(dataTypeClass = String.class, paramType = "body", name = "realName", value = "名字", required = true)
})
@PutMapping("/updateUserInfo")
public String updateUser(@RequestHeader String id, @RequestParam String userName, @PathVariable String passWord, @RequestBody String realName){
return "{'id': " + id + ", 'userName':" + userName + ", 'passWord':" + passWord + ", 'realName':" + realName +"}";
}
@ApiImplicitParam用於描述方法的參數,標註在方法上,和@ApiParam功能一樣,只是標註的位置不同而已
- paramType:參數類型,即參數放在哪個地方
- header–>請求參數的獲取:@RequestHeader,參數放在請求頭
- query–>請求參數的獲取:@RequestParam,參數追加在url後面
- path(用於restful接口)–>請求參數的獲取:@PathVariable
- body 使用@RequestBody接收數據 POST有效,參數放在請求體中
- name:參數名
- dataType:參數的數據類型
- required:參數是否必須傳
- value:參數的描述
- defaultValue:參數的默認值
@ApiImplicitParams: 用於包含多個@ApiImplicitParam
@ApiModelProperty(value = "當前頁", required = true)
private Integer page;
@ApiModelProperty(value = "每頁記錄數", required = true)
private Integer pageSize;
@ApiModel:描述一個Model的信息(這種一般用在post創建的時候,使用@RequestBody這樣的場景,請求參數無法使用@ApiImplicitParam註解進行描述的時候)
@ApiModelProperty:描述一個model的屬性
- value 參數名稱
- required 是否必須 boolean
- hidden 是否隱藏 boolean
@ApiIgnore:用於或略該接口,不生成該接口的文檔
測試
啓動項目後訪問http://localhost:8082/bootbuliding/swagger-ui.html
擴展
集成第三方的 swagger 來替換原生的 swagger,美化文檔樣式
pom.xml
去除原有的swagger依賴更換爲如下配置
<dependency>
<groupId>com.battcn</groupId>
<artifactId>swagger-spring-boot-starter</artifactId>
<version>${battcn.swagger.version}</version>
</dependency>
application.yml
spring:
swagger:
#是否開啓
enabled: true
title: SpringBootBuilding系統構建
description: 這是一個描述
version: 1.0.0-SNAPSHOT
contact:
name: Lison
email: [email protected]
# swagger掃描的基礎包,默認:全掃描
#base-package:
#需要處理的基礎URL規則,默認:/**
#base-path:
#需要排除的URL規則,默認:空
#exclude-path:
security:
filter-plugin: true
username: Lison
password: 123456
#是否啓用 swagger登陸驗證
global-response-messages:
GET[0]:
code: 400
message: Bad Request,一般爲請求參數不對
GET[1]:
code: 404
message: NOT FOUND,一般爲請求路徑不對
GET[2]:
code: 500
message: ERROR,一般爲程序內部錯誤
POST[0]:
code: 400
message: Bad Request,一般爲請求參數不對
POST[1]:
code: 404
message: NOT FOUND,一般爲請求路徑不對
POST[2]:
code: 500
message: ERROR,一般爲程序內部錯誤
參考文檔
- https://github.com/battcn/swagger-spring-boot/blob/master/README.md
- 幾款比較好看的swagger-ui,具體使用方法參見各個依賴的官方文檔:
- battcn 的 swagger-spring-boot-starter 文檔:https://github.com/battcn/swagger-spring-boot/blob/master/README.md
- swagger-ui-layer 文檔:https://gitee.com/caspar-chen/Swagger-UI-layer#%E5%A6%82%E4%BD%95%E4%BD%BF%E7%94%A8
- swagger-bootstrap-ui 文檔:https://gitee.com/xiaoym/swagger-bootstrap-ui#%E4%BD%BF%E7%94%A8%E8%AF%B4%E6%98%8E
- swagger-ui-themes 文檔:https://github.com/ostranme/swagger-ui-themes#getting-started