1.swagger介紹html
如今開發,不少採用先後端分離的模式,前端只負責調用接口,進行渲染,前端和後端的惟一聯繫,變成了API接口。所以,API文檔變得愈來愈重要。swagger是一個方便咱們更好的編寫API文檔的框架,並且swagger能夠模擬http請求調用。前端
大部分採起的方式:Vue + SpringBoot,Vue經過js渲染頁面,後端把數據傳遞給js,早期前端只負責寫頁面,而後把寫好的HTML頁面給後端,後端使用模板引擎(Jsp,Thymeleaf、 freemarker)進行開發。web
先後端分離的好處:各自開發,相對獨立,鬆耦合,先後端經過API進行交互,後端提供接口給前端,前端去調用該接口,但可能會致使先後端團隊人員不能作到及時協商,出現一些問題。解決方式:早期使用實時更新文檔,但很是繁瑣,後來又使用postman來進行一些測試。spring
swagger是目前最流行的Api框架,官網:https://swagger.io/後端
2.springboot中集成swagger使用步驟:api
導入依賴springboot
<dependency> <artifactId>springfox-swagger-ui</artifactId> <version>2.9.2</version> </dependency> <dependency> <artifactId>springfox-swagger2</artifactId> <version>2.9.2</version> </dependency> |
建立配置類
@Configuration
//
開啓Swagger2
public class SwaggerConfig { } |
而後啓動測試運行,訪問:http://localhost:8080/swagger-ui.html,看到以下頁面:
手動配置實例,修改SwaggerConfig配置類
package com.qf.swagger.config;
//
開啓Swagger2
public class SwaggerConfig {
//
配置Swagger的Bean實例
@Bean public Docket swaggerSpringMvcPlugin() { return new Docket(DocumentationType.
SWAGGER_2
).apiInfo(apiInfo()); }
//
配置API的基本信息(會在http://項目實際地址/swagger-ui.html頁面顯示)
private ApiInfo apiInfo() { return new ApiInfoBuilder() .title("測試API文檔標題") .description("測試api接口文檔描述") .termsOfServiceUrl("http://www.baidu.com") .version("1.0") .build(); } } |
而後再次重啓測試運行:
建立實體類
package com.qf.swagger.entity; public void setPassword(String password) { this.password = password; |
建立controller
package com.qf.swagger.controller; } |
修改SwaggerConfig配置類
package com.qf.swagger.config;
//
開啓Swagger2
public class SwaggerConfig {
//
配置Swagger的Bean實例
@Bean public Docket swaggerSpringMvcPlugin() { return new Docket(DocumentationType.
SWAGGER_2
).apiInfo(apiInfo()) .groupName("yangl")
//
分組名稱(能夠建立多個Docket就有多個組名)
.enable(true)
//enable
表示是否開啓Swagger
.select()
//RequestHandlerSelectors
指定掃描的包
.apis(RequestHandlerSelectors.
basePackage
("com.qf.swagger.controller")).build();
//
配置API的基本信息(會在http://項目實際地址/swagger-ui.html頁面顯示)
private ApiInfo apiInfo() { return new ApiInfoBuilder() .title("測試API文檔標題") .description("測試api接口文檔描述") .termsOfServiceUrl("http://www.baidu.com") .version("1.0") .build(); } } |
swagger經過註解代表該接口會生成文檔,包括接口名、請求方法、參數、返回信息
@Api:修飾整個類,描述Controller的做用
@ApiOperation:描述一個類的一個方法,或者說一個接口
@ApiModel:用對象來接收參數 ,修飾類
@ApiModelProperty:用對象接收參數時,描述對象的一個字段
@ApiResponse:HTTP響應其中1個描述
@ApiResponses:HTTP響應總體描述,通常描述錯誤的響應
@ApiIgnore:使用該註解忽略這個API
@ApiError :發生錯誤返回的信息
@ApiParam:單個參數描述
@ApiImplicitParam:一個請求參數,用在方法上
@ApiImplicitParams:多個請求參數