在我們的傳統(tǒng)項(xiàng)目中仍稀,對(duì)前后端的API接口約定夺荒,一般有寫(xiě)成接口文檔,或者公司內(nèi)部口頭交流歪脏,或者其它方式疑俭,但這幾種方式都給我們的協(xié)同工作中帶來(lái)了或多或少的不便之處,那么就有了一些工具的出現(xiàn)來(lái)對(duì)我們的協(xié)同工作帶來(lái)便利婿失。這種工具選擇面還是挺多的钞艇,有swagger啄寡,jdoc,apiDoc等香璃。
目前我在工作中寫(xiě)得較多的就是API接口这难,項(xiàng)目大部分都采用springBoot編寫(xiě),集成了swagger2來(lái)作為生成API+測(cè)試葡秒,總體上挺好使用的姻乓,話不多說(shuō),直接步入正題眯牧。
一蹋岩、依賴包引入
pom.xml中引人依賴
<!-- swagger2 -->
<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>
二、配置
2.1 在springBoot配置文件application.yml中加入如下配置:
#swagger 配置
swagger:
title: API示例
desc: 基于springBoot編寫(xiě)的RESful-API
version: 0.0.1.SNAPSHOT
termsOfServiceUrl: javascript:void(0)
license: Apache 2.0
licenseUrl: http://www.apache.org/licenses/LICENSE-2.0.html
basePackage: com.restful.api.demo.web
groupName: 默認(rèn)API示例分組
contactName: wendell
contactUrl: https://github.com/wendell-dev/restful-api-demo.git
contactEmail: wendell-dev@foxmail.com
2.2 新建配置類
類頭部主要聲明了配置注解和啟用swagger2注解
/**
* 對(duì)Swagger2的配置信息
*
* @author wendell
*/
@Configuration
@EnableSwagger2
@ConfigurationProperties(prefix = "swagger")
public class Swagger2Config {
private String title;
private String desc;
private String version;
private String termsOfServiceUrl;
private String license;
private String licenseUrl;
private String basePackage;
private String groupName;
private String contactName;
private String contactUrl;
private String contactEmail;
private ApiInfo apiInfo() {
return new ApiInfoBuilder().title(title).description(desc).version(version).termsOfServiceUrl(termsOfServiceUrl)
.licenseUrl(licenseUrl).license(license).contact(new Contact(contactName, contactUrl, contactEmail))
.build();
}
@Bean
public Docket swaggerApi() {
return new Docket(DocumentationType.SWAGGER_2).apiInfo(apiInfo()).groupName(groupName)
.directModelSubstitute(LocalDate.class, String.class).genericModelSubstitutes(ResponseEntity.class)
.useDefaultResponseMessages(false)
.globalResponseMessage(RequestMethod.POST, customerResponseMessage())
.globalResponseMessage(RequestMethod.GET, customerResponseMessage())
.forCodeGeneration(true).select()
.apis(RequestHandlerSelectors.basePackage(basePackage))
.apis(RequestHandlerSelectors.withMethodAnnotation(ApiOperation.class)).paths(PathSelectors.any())
.build();
}
private List<ResponseMessage> customerResponseMessage() {
List<ResponseMessage> list = new ArrayList<>();
list.add(new ResponseMessageBuilder().code(200).message("請(qǐng)求成功").build());
list.add(new ResponseMessageBuilder().code(201).message("資源創(chuàng)建成功").build());
list.add(new ResponseMessageBuilder().code(204).message("服務(wù)器成功處理了請(qǐng)求学少,但不需要返回任何實(shí)體內(nèi)容").build());
list.add(new ResponseMessageBuilder().code(400).message("請(qǐng)求失敗,具體查看返回業(yè)務(wù)狀態(tài)碼與對(duì)應(yīng)消息").build());
list.add(new ResponseMessageBuilder().code(401).message("請(qǐng)求失敗,未經(jīng)過(guò)身份認(rèn)證").build());
list.add(new ResponseMessageBuilder().code(405).message("請(qǐng)求方法不支持").build());
list.add(new ResponseMessageBuilder().code(415).message("請(qǐng)求媒體類型不支持").build());
list.add(new ResponseMessageBuilder().code(500).message("服務(wù)器遇到了一個(gè)未曾預(yù)料的狀況,導(dǎo)致了它無(wú)法完成對(duì)請(qǐng)求的處理").build());
list.add(new ResponseMessageBuilder().code(503).message("服務(wù)器當(dāng)前無(wú)法處理請(qǐng)求,這個(gè)狀況是臨時(shí)的剪个,并且將在一段時(shí)間以后恢復(fù)").build());
return list;
}
// setter/getter略
}
三、controller中使用
需要在controller層的類頭部以及方法頭部侵入代碼了版确,主要用到一些io.swagger.annotations下的注解
/**
* 測(cè)試接口 - controller類
*
* @author wendell
*/
@Api(tags = "測(cè)試接口")
@RestController
@RequestMapping(value = "/tests")
public class TestController {
@ApiOperation(value = "測(cè)試 - GET請(qǐng)求參數(shù)")
@ApiImplicitParams({
@ApiImplicitParam(name = "id", value = "編號(hào)", required = true, paramType = "query"),
@ApiImplicitParam(name = "name", value = "名稱", required = false, paramType = "query")
})
@GetMapping
public ResponseEntity<String> test(@RequestParam Long id, @RequestParam String name) {
return ResponseEntity.ok("編號(hào): " + id + "名稱: " + name);
}
}
四扣囊、啟動(dòng)springBoot應(yīng)用
接著我們啟動(dòng)我們的springBoot應(yīng)用,訪問(wèn)swagger2自帶的入口頁(yè)面地址 http://localhost/swagger-ui.html , 下圖就是生成的API接口绒疗,可以點(diǎn)擊左下方的 [Try it out!] 按鈕進(jìn)行http請(qǐng)求測(cè)試侵歇,非常方便。
五吓蘑、加入統(tǒng)一參數(shù)
大部分時(shí)候惕虑,我們編寫(xiě)的API接口都需要登錄后訪問(wèn),一般我們都是統(tǒng)一驗(yàn)證請(qǐng)求header里面的token參數(shù)磨镶,那么類似這種參數(shù)就應(yīng)該統(tǒng)一處理溃蔫,而不是在所有需要的controller方法中都加上token參數(shù),類似下面這種 不恰當(dāng) 用法:
@ApiOperation(value = "測(cè)試 - GET請(qǐng)求加入header參數(shù)")
@ApiImplicitParams({
@ApiImplicitParam(name = "token", value = "請(qǐng)求token", required = true, paramType = "header"),
})
@GetMapping
public ResponseEntity<String> test(@RequestHeader String token) {
return ResponseEntity.ok("token:" + token);
}
我們應(yīng)該在swagger的配置類中統(tǒng)一處理token參數(shù)琳猫,只需要修改我們上面2.2步驟中Swagger2Config類即可伟叛,如下這樣的方式:
@Bean
public Docket swaggerApi() {
// ==================== 需要的參數(shù) START ====================
List<Parameter> pars = new ArrayList<>();
ParameterBuilder token = new ParameterBuilder();
token.name("token").description("token").modelRef(new ModelRef("string")).parameterType("header").required(false).build();
pars.add(token.build());
// ==================== 需要的參數(shù) END ====================
return new Docket(DocumentationType.SWAGGER_2).apiInfo(apiInfo()).groupName(groupName)
.globalOperationParameters(pars) // 全局參數(shù)
.directModelSubstitute(LocalDate.class, String.class).genericModelSubstitutes(ResponseEntity.class)
.useDefaultResponseMessages(false)
.globalResponseMessage(RequestMethod.POST, customerResponseMessage())
.globalResponseMessage(RequestMethod.GET, customerResponseMessage())
.forCodeGeneration(true).select()
.apis(RequestHandlerSelectors.basePackage(basePackage))
.apis(RequestHandlerSelectors.withMethodAnnotation(ApiOperation.class)).paths(PathSelectors.any())
.build();
}
接下來(lái)我們?cè)俅卧L問(wèn)swagger2自帶的入口頁(yè)面地址,看看效果:
可以看見(jiàn)沸移,我們的接口中已經(jīng)多了一個(gè)非必填的參數(shù)token痪伦,而且參數(shù)是在請(qǐng)求header中。
六雹锣、結(jié)束語(yǔ)
好了网沾,關(guān)于springBoot集成swagger2的方式就介紹到這里,文中介紹的方式絕大部分方式都是基于我自己在工作中的使用方式蕊爵,已經(jīng)能夠滿足大部分的接口文檔需求了辉哥。 當(dāng)然還有一些高級(jí)點(diǎn)的特征沒(méi)有介紹到,如分組之類,其實(shí)就是在配置文件上下文章醋旦,需要的時(shí)候自行g(shù)oogle一下即可恒水。