參考:
http://blog.csdn.net/amon1991/article/details/76774880
http://blog.didispace.com/springbootrestfulapi/
一宛渐、為什么要用swagger2
1.手動錄入API的缺點:
1)由于需求或設(shè)計的原因,并不能保證一次就可將接口確定,不再做變動踩晶,頻繁的修改接口可能會導(dǎo)致接口文檔和實際接口不一致茁瘦;
2)不能直接在線測試接口忧勿,需使用其他工具补胚,如postman
2.解決方案
swagger完美解決了以上兩個問題蒂教,既能在線測試接口肾扰,又能動態(tài)生成api文檔畴嘶,只需在接口上加適當(dāng)?shù)膫渥ⅰ?/p>
3.swagger缺點
1)代碼侵入性強(qiáng)
2)必須啟動接口服務(wù)器,才能訪問到接口文檔
二集晚、swagger2使用
1.添加pom依賴
添加swagger2核心包和swagger-ui界面包窗悯。
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>2.8.0</version>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>2.8.0</version>
</dependency>
2.配置api文檔頁基本信息
與啟動類同級,特別注意里面配置了API文件也就是controller的路徑偷拔,不然生成的文檔掃描不到接口蒋院。
@Configuration
@EnableSwagger2
public class Swagger2{
@Bean
public Docket createRestApi() {
return new Docket(DocumentationType.SWAGGER_2)
.apiInfo(apiInfo())
.select()
.apis(RequestHandlerSelectors.basePackage("com.xx.web.controller"))
.paths(PathSelectors.any())
.build();
}
private ApiInfo apiInfo() {
return new ApiInfoBuilder()
.title("xx項目 RESTful APIs")
.description("xx項目后臺api接口文檔")
.version("1.0")
.build();
}
}
spring-boot和swagger整合時,可以通過注解注入相關(guān)配置条摸。通過這些配置可指定在spring-boot啟動時掃描哪些controller層的文件夾悦污,另外可指定api文檔頁的標(biāo)題和描述信息等內(nèi)容。
3.API文檔編寫示例
一般在controller層钉蒲,將詳盡的API接口輸入輸出在代碼中通過注解進(jìn)行相關(guān)描述切端。
@Api(value = "PageController", description = "用戶登錄登出接口")
@Controller
@RequestMapping("/")
public classPageController{
@ApiOperation(value="用戶登錄", notes="用戶登錄接口")
@ApiImplicitParams({
@ApiImplicitParam(name = "username", value = "用戶名", required = true ,dataType = "string"),
@ApiImplicitParam(name = "passwd", value = "密碼", required = true ,dataType = "string")
})
@RequestMapping(value = "/login",method = {RequestMethod.POST,RequestMethod.GET})
@ResponseBody
public ModelMap login(Users data, HttpServletRequest request){
xxx...
}
}