一积瞒、Swagger2 簡(jiǎn)介
??由于Spring Boot能夠快速開發(fā)君仆、便捷部署等特性最爬,相信有很大一部分Spring Boot的用戶會(huì)用來(lái)構(gòu)建RESTful API。而我們構(gòu)建RESTful API的目的通常都是由于多終端的原因汪疮,這些終端會(huì)共用很多底層業(yè)務(wù)邏輯峭火,因此我們會(huì)抽象出這樣一層來(lái)同時(shí)服務(wù)于多個(gè)移動(dòng)端或者Web前端。
??這樣一來(lái)智嚷,我們的RESTful API就有可能要面對(duì)多個(gè)開發(fā)人員或多個(gè)開發(fā)團(tuán)隊(duì):IOS開發(fā)卖丸、Android開發(fā)或是Web開發(fā)等。為了減少與其他團(tuán)隊(duì)平時(shí)開發(fā)期間的頻繁溝通成本盏道,傳統(tǒng)做法我們會(huì)創(chuàng)建一份RESTful API文檔來(lái)記錄所有接口細(xì)節(jié)稍浆,然而這樣的做法有以下幾個(gè)問(wèn)題:
??由于接口眾多,并且細(xì)節(jié)復(fù)雜(需要考慮不同的HTTP請(qǐng)求類型摇天、HTTP頭部信息粹湃、HTTP請(qǐng)求內(nèi)容等),高質(zhì)量地創(chuàng)建這份文檔本身就是件非常吃力的事泉坐,下游的抱怨聲不絕于耳。
??隨著時(shí)間推移裳仆,不斷修改接口實(shí)現(xiàn)的時(shí)候都必須同步修改接口文檔腕让,而文檔與代碼又處于兩個(gè)不同的媒介,除非有嚴(yán)格的管理機(jī)制歧斟,不然很容易導(dǎo)致不一致現(xiàn)象纯丸。
??為了解決上面這樣的問(wèn)題,本文將介紹RESTful API的重磅好伙伴Swagger2静袖,它可以輕松的整合到Spring Boot中觉鼻,并與Spring MVC程序配合組織出強(qiáng)大RESTful API文檔。它既可以減少我們創(chuàng)建文檔的工作量队橙,同時(shí)說(shuō)明內(nèi)容又整合入實(shí)現(xiàn)代碼中坠陈,讓維護(hù)文檔和修改代碼整合為一體,可以讓我們?cè)谛薷拇a邏輯的同時(shí)方便的修改文檔說(shuō)明捐康。另外Swagger2也提供了強(qiáng)大的頁(yè)面測(cè)試功能來(lái)調(diào)試每個(gè)RESTful API仇矾。具體效果如下圖所示:
二、Maven依賴
<!--swagger-->
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>2.9.2</version>
<exclusions>
<exclusion>
<groupId>io.swagger</groupId>
<artifactId>swagger-annotations</artifactId>
</exclusion>
<exclusion>
<groupId>io.swagger</groupId>
<artifactId>swagger-models</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>io.swagger</groupId>
<artifactId>swagger-annotations</artifactId>
<version>1.5.21</version>
</dependency>
<dependency>
<groupId>io.swagger</groupId>
<artifactId>swagger-models</artifactId>
<version>1.5.21</version>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>2.9.2</version>
</dependency>
<!--swagger插件-->
<dependency>
<groupId>com.github.xiaoymin</groupId>
<artifactId>swagger-bootstrap-ui</artifactId>
<version>1.9.3</version>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-bean-validators</artifactId>
<version>2.9.2</version>
</dependency>
三解总、配置文件
1. 配置文件
@Configuration
@EnableSwagger2
@EnableSwaggerBootstrapUI
@Import(BeanValidatorPluginsConfiguration.class)
public class Swagger2Config {
@Bean
public Docket controllerApi() {
return new Docket(DocumentationType.SWAGGER_2)
.apiInfo(apiInfo())
.groupName("默認(rèn)接口")
.select()
.apis(RequestHandlerSelectors.basePackage("com.xxxx.admin.modules.system.controller.admin"))
.paths(PathSelectors.any())
.build();
}
private ApiInfo apiInfo() {
return new ApiInfoBuilder()
.title("XXXXXXXXX")
.description("描述:XXXXXXX贮匕!")
.termsOfServiceUrl("http://www.xtsz.com/")
.contact(new Contact("marquis","http://www.XXXXXX.com/","XXXXXXX@qq.com"))
.version("版本號(hào):1.0.0")
.build();
}
/**
* 安全認(rèn)證
* @return
*/
List<SecurityReference> defaultAuth() {
AuthorizationScope authorizationScope = new AuthorizationScope("global", "accessEverything");
AuthorizationScope[] authorizationScopes = new AuthorizationScope[1];
authorizationScopes[0] = authorizationScope;
return Lists.newArrayList(new SecurityReference("BearerToken", authorizationScopes));
}
List<SecurityReference> defaultAuth1() {
AuthorizationScope authorizationScope = new AuthorizationScope("global", "accessEverything");
AuthorizationScope[] authorizationScopes = new AuthorizationScope[1];
authorizationScopes[0] = authorizationScope;
return Lists.newArrayList(new SecurityReference("BearerToken1", authorizationScopes));
}
}
2. 權(quán)限設(shè)置
// swagger-ui
.antMatchers("/swagger-ui.html").permitAll()
.antMatchers("/doc.html").permitAll()
.antMatchers("/swagger-resources/**").permitAll()
.antMatchers("/images/**").permitAll()
.antMatchers("/webjars/**").permitAll()
.antMatchers("/v2/api-docs").permitAll()
.antMatchers("/configuration/ui").permitAll()
.antMatchers("/configuration/security").permitAll()
// swagger-ui
3. 瀏覽訪問(wèn):
http://localhost:8000/doc.html
4. 全局設(shè)置
四、相關(guān)注解
swagger通過(guò)注解表明該接口會(huì)生成文檔花枫,包括接口名刻盐、請(qǐng)求方法掏膏、參數(shù)、返回信息的等等敦锌。
@Api:修飾整個(gè)類壤追,描述Controller的作用
@ApiOperation:描述一個(gè)類的一個(gè)方法,或者說(shuō)一個(gè)接口
@ApiParam:?jiǎn)蝹€(gè)參數(shù)描述
@ApiModel:用對(duì)象來(lái)接收參數(shù)
@ApiProperty:用對(duì)象接收參數(shù)時(shí)供屉,描述對(duì)象的一個(gè)字段
@ApiResponse:HTTP響應(yīng)其中1個(gè)描述
@ApiResponses:HTTP響應(yīng)整體描述
@ApiIgnore:使用該注解忽略這個(gè)API
@ApiError :發(fā)生錯(cuò)誤返回的信息
@ApiParamImplicit:一個(gè)請(qǐng)求參數(shù)
@ApiParamsImplicits: 多個(gè)請(qǐng)求參數(shù)
五行冰、注解使用
- 實(shí)體類注解
@ApiModelProperty()用于方法,字段伶丐; 表示對(duì)model屬性的說(shuō)明或者數(shù)據(jù)操作更改
value–字段說(shuō)明
name–重寫屬性名字
dataType–重寫屬性類型
required–是否必填
example–舉例說(shuō)明
hidden–隱藏
@Data
@ApiModel
public class LoginUser {
@NotNull(message = "賬號(hào)不能為空")
@ApiModelProperty(value = "賬號(hào)", required = true)
private String username;
@NotNull(message = "密碼不能為空")
@ApiModelProperty(value = "登錄密碼", required = true)
private String password;
@ApiModelProperty(value="記住密碼 0不記 1記住",required = true,example="0")
private Integer rememberMe;
}
- 控制器類注解
@Api:用在請(qǐng)求的類上悼做,表示對(duì)類的說(shuō)明
tags="說(shuō)明該類的作用,可以在UI界面上看到的注解"
value="該參數(shù)沒(méi)什么意義哗魂,在UI界面上也看到肛走,所以不需要配置"
@Api(tags = {"1、用戶登錄"})
public class AuthController {
}
- 控制器方法注解
@ApiOperation() 用于方法录别;表示一個(gè)http請(qǐng)求的操作
value用于方法描述
notes用于提示內(nèi)容
tags可以重新分組(視情況而用)
@PostMapping("/login")
@ApiOperation(value = "1朽色、用戶登錄", notes = "使用賬號(hào)密碼登錄", httpMethod = "POST")
public String login(@RequestBody LoginUser loginUser){
}
- @ApiImplicitParam
在 Rest 接口上單獨(dú)使用
@ApiImplicitParam 在 Rest 接口上單獨(dú)使用的時(shí)候,表示單個(gè)請(qǐng)求參數(shù)
在 Rest 接口上和 @ApiImplicitParams 組合使用
@ApiImplicitParam 在 Rest 接口上和 @ApiImplicitParams 組合時(shí)候组题,表示多個(gè)請(qǐng)求參數(shù)
屬性
屬性名稱 | 數(shù)據(jù)類型 | 默認(rèn)值 | 說(shuō)明 |
---|---|---|---|
name | String | “” | 參數(shù)名稱(實(shí)體類字段名稱) |
value | String | “” | 參數(shù)簡(jiǎn)要說(shuō)明 |
defaultValue | String | “” | 描述參數(shù)的默認(rèn)值 |
allowableValues | String | “” | 限制此參數(shù)接收的值葫男,可使用的值或值得范圍 |
required | boolean | false | 指定是否為必填參數(shù),false:非必傳參數(shù); true:必傳參數(shù) |
access | String | “” | 參數(shù)過(guò)濾,參考: io.swagger.core.filter.SwaggerSpecFilte |
allowMultiple | boolean | false | 指定參數(shù)是否可以通過(guò)多次出現(xiàn)來(lái)接收多個(gè)值 |
dataType | String | “” | 參數(shù)的數(shù)據(jù)類型崔列,可以使類名或原始數(shù)據(jù)類型 |
dataTypeClass | Class<?> | Void.class | 參數(shù)的類梢褐,如果提供則覆蓋 dataType |
paramType | String | “” | 參數(shù)的參數(shù)類型,有效值為 path, query, body, header, form |
example | String | “” | 非請(qǐng)求體(body)參數(shù)的單個(gè)請(qǐng)求示例 |
examples | Example | @Example(value = @ExampleProperty(mediaType = “”, value = “”)) | 參數(shù)示例赵讯,僅適用于 BodyParameters(請(qǐng)求體類型的) |
type | String | “” | 添加覆蓋檢測(cè)到的類型的功能 |
format | String | “” | 添加提供自定義格式的功能 |
allowEmptyValue | boolean | false | 添加將 format 設(shè)置為空的功能 |
readOnly | boolean | false | 添加被指定為只讀的能力 |
collectionFormat | String | “” | 添加使用 array 類型 collectionFormat 的功能 |
paramType屬性:
header : 請(qǐng)求參數(shù)的獲扔取:@RequestHeader
query : 請(qǐng)求參數(shù)的獲取:@RequestParam
path : 請(qǐng)求參數(shù)的獲缺咭怼:@PathVariable
body : 請(qǐng)求參數(shù)的獲扔阆臁:@RequestBody
form : 不常用
- @ApiImplicitParams
在 Rest 接口方法上使用來(lái)指定請(qǐng)求參數(shù)
屬性
屬性名稱 | 數(shù)據(jù)類型 | 默認(rèn)值 | 說(shuō)明 |
---|---|---|---|
value | ApiImplicitParam[] | API 可用的 | 參數(shù)列表 |
@GetMapping("/getUserName")
@ApiOperation(value = "1、獲取賬號(hào)名稱", notes = "使用賬號(hào)密碼登錄", httpMethod = "GET")
@ApiImplicitParams({
@ApiImplicitParam(name = "username", value = "賬號(hào)名稱", dataType = "String"),
@ApiImplicitParam(name = "password", value = "密碼", dataType = "String")})
public String getUserName(String username, String password, HttpServletRequest request) {
String str = "本地端口:" + request.getLocalPort() + "遠(yuǎn)程端口:" + request.getRemotePort() + "服務(wù)端口:" + request.getServerPort();
return "用戶名為:" + username + "密碼:" + password + "---->" + str;
}
六组底、權(quán)限控制
生產(chǎn)環(huán)境不可調(diào)用查看丈积。
在Swagger2的配置類上添加注解。
@Profile({"dev", "test"})