Swagger?的目標(biāo)是為REST API 定義一個標(biāo)準(zhǔn)的,與語言無關(guān)的接口,使人和計算機在看不到源碼或者看不到文檔或者不能通過網(wǎng)絡(luò)流量檢測的情況下能發(fā)現(xiàn)和理解各種服務(wù)的功能。當(dāng)服務(wù)通過Swagger定義,消費者就能與遠程的服務(wù)互動通過少量的實現(xiàn)邏輯。
簡單說,swagger能夠根據(jù)代碼中的注釋自動生成api文檔,并且提供測試接口;
swagger和swagger2是兩個不同的版本,現(xiàn)在用的比較多的是swagger和springfox,springfox就是swagger-springmvc的升級版,也叫swagger2;
使用springfox;
集成springfox和springmvc:
//添加依賴
<!-- swagger2 start -->
<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>
<!-- swagger2 end -->
@Configuration
@EnableSwagger2
public class ApiConfig {
@Bean
public Docket docket() {
return new Docket(DocumentationType.SWAGGER_2)
.apiInfo(apiInfo())
.select()
.apis(RequestHandlerSelectors.basePackage("cn.wolfcode"))//掃描路徑
// .apis(RequestHandlerSelectors.withMethodAnnotation(ApiImplicitParams.class))//根據(jù)注解定制
.paths(PathSelectors.any()) //定義哪些路徑的接口需要生成文檔
.build();
}
@Bean
public ApiInfo apiInfo() {
Contact contact = new Contact("sky","http://m.itdecent.cn/u/a099a2677722","8888@126.com");
return new ApiInfoBuilder()
.title("Spring Boot中使用Swagger2構(gòu)建RESTful API")//文檔首頁標(biāo)題
.description("swagger2-文檔構(gòu)建利器")//文檔描述信息
.contact(contact) //創(chuàng)建者信息
.version("1.0") //文檔版本
.build();
}
}
訪問地址:http://localhost:8080/v2/api-docs
ui訪問地址:http://localhost:8080/swagger-ui.html
springfox的標(biāo)簽:
@Api(value = "用戶增刪改查",description = "詳細描述")
@RestController
@RequestMapping("/users")
public class EmpController {
//獲取用戶列表
@ApiOperation(value = "獲取用戶列表",notes = "獲取用戶列表詳細描述")
@GetMapping
public List<Emp> getUsers(){
List list = new ArrayList<>();
list.add(new Emp(1L,"A"));
list.add(new Emp(2L,"B"));
list.add(new Emp(3L,"C"));
return list;
}
//獲取用戶
/*
params = "pwd=999"
headers = "Content-Type=application/json" == "Accept=application/json"
headers="contentType=application/json" == consumes="application/json"
*/
@RequestMapping(value = "/{id}",method = RequestMethod.GET)
public Emp getUser(@PathVariable("id") Long id){
System.out.println("id : "+id);
return new Emp(1L,"xx");
}
//刪除用戶
@ApiImplicitParams({
@ApiImplicitParam(name = "id",value = "用戶的唯一標(biāo)識",required = true),
@ApiImplicitParam(name = "name" ,value = "用戶名" , required = false)
})
@ApiResponses({
@ApiResponse(code = 401 ,message = "禁止訪問")
})
@DeleteMapping("/{id}/{name}")
public void deleteUsers(@PathVariable("id") Long id ,@PathVariable("name") String name){
System.out.println("刪除成功...");
}
//創(chuàng)建用戶
@ApiIgnore
@PostMapping
public Emp createUsers(@RequestBody Emp emp){
System.out.println(emp);
return emp;
}
}
swagger2優(yōu)點: 簡單 , 實時 , 可測試 , 容易管理
swagger2缺點: 代碼侵入性太強, 影響正常代碼閱讀
學(xué)習(xí)swagger2就是學(xué)習(xí)怎么使用注解為接口添加描述信息
@Api:修飾整個類,描述Controller的作用
@ApiOperation:描述一個類的一個方法,或者說一個接口
@ApiImplicitParams:多個請求參數(shù)
@ApiImplicitParam:一個請求參數(shù)
@ApiResponses:HTTP響應(yīng)整體描述
@ApiResponse:HTTP響應(yīng)其中1個描述
@ApiModel:用對象來接收參數(shù)
@ApiModelProperty:用對象接收參數(shù)時,描述對象的一個字段
@ApiIgnore:使用該注解忽略這個API
類和方法的描述:
@Api修飾整個類,描述Controller的作用
@ApiOperation 貼在方法上,描述一個方法的作用
1、@Api注解的使用:貼在類上,主要用下面的這幾個屬性
1)value:該controller簡短的標(biāo)題
2)description:詳細介紹
3)producer:說明該controller是使用什么顯示層格式的
4)protocols:使用什么協(xié)議
2、@ApiOperation注解的使用:貼在方法上,主要用下面的這幾個屬性
1)value:該方法簡短的變態(tài)
2)note:詳細介紹
3)code:正常情況下返回的狀態(tài)碼是多少
4)httpMethod:使用什么http方法
5)response:響應(yīng)什么對象,這里寫的是響應(yīng)的對象的字節(jié)碼
/**
*
* @param param
* @return
*/
@ApiOperation(value = "獲取所有產(chǎn)品信息", notes = "獲取所有產(chǎn)品信息", httpMethod = "GET")
@ResponseBody
@RequestMapping(value="/sync/test", method = RequestMethod.GET)
public JSONMessage test(String value,String notes) {
return JSONMessage.success("測試功能");
}
參數(shù)的描述:
貼在參數(shù)上
@ApiImplicitParams 多個請求參數(shù)
@ApiImplicitParam 一個請求參數(shù)
@ApiParam 單個參數(shù)描述
1)name:參數(shù)名
2)value:參數(shù)名對應(yīng)的值
3)dataType:參數(shù)的類型
4)require:該參數(shù)是否必填
5)paramType:該參數(shù)的來源類型,它的值有如下:
query:該參數(shù)從地址欄問號后面的參數(shù)獲取
form:該參數(shù)從form表單中獲取
path:該參數(shù)從URL地址上獲取
body:該參數(shù)從請求體中獲取
header:該參數(shù)從請求頭獲取
響應(yīng)的描述:
@ApiResponses:HTTP響應(yīng)整體的描述
@ApiResponse:HTTP響應(yīng)中某一種響應(yīng)的描述
用在@ApiResponses中,一般用于表達一個錯誤的響應(yīng)信息(200相應(yīng)不寫在這里面)
code:數(shù)字,例如400
message:信息,例如"請求參數(shù)沒填好"
response:拋出的異常類
對象模型描述:
@ApiModel/@ApiModelProperty
@ApiModel:描述一個Model的信息(這種一般用在post創(chuàng)建的時候,使用@RequestBody這樣的場景,請求參數(shù)無法使用@ApiImplicitParam注解進行描述的時候)
@ApiModelProperty:描述一個model的屬性
忽略接口API:
@ApiIgnore 貼了該注解的api 會被忽略,不生成接口文檔
兩種不生成api的方式:
1、@ApiIgnore:可以貼在類和方法上
2、在swagger配置類上的select()方法上調(diào)用apis(),apis方法需要傳入一個selector??梢允褂肦equestHandlerSelector內(nèi)置的selector
springBoot集成swagger2:
//添加依賴
<!-- swagger2 start -->
<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>
<!-- swagger2 end -->
@Configuration
@EnableSwagger2
public class SwaggerConfig{
@Bean
public Docket createRestApi() {
return new Docket(DocumentationType.SWAGGER_2)
.apiInfo(apiInfo())
.select()
// .apis(RequestHandlerSelectors.basePackage("cn.wolfcode.controller"))//掃描路徑
.apis(RequestHandlerSelectors.withMethodAnnotation(ApiImplicitParams.class))//根據(jù)注解定制
.paths(PathSelectors.any()) //定義哪些路徑的接口需要生成文檔
.build();
}
@Bean
private ApiInfo apiInfo() {
Contact contact = new Contact("sky","http://m.itdecent.cn/u/a099a2677722","8888@126.com");
return new ApiInfoBuilder()
.title("Spring Boot中使用Swagger2構(gòu)建RESTful API")//文檔首頁標(biāo)題
.description("swagger2-文檔構(gòu)建利器")//文檔描述信息
.contact(contact) //創(chuàng)建者信息
.version("1.0") //文檔版本
.build();
}
}