1. swagger出現的背景?
現在的網站架構,前後端分離已經成爲一種趨勢,前後端的技術在各自的道路上越走遠越,後端的框架有常見的spring全家桶,前段也有angular和react等框架。後端主要負責提供服務接口,前段主要負責渲染圖形界面,而且前段的展示形式也在多樣化,有web端,手機端等。聯繫前端和後端的主要紐帶就是約定好的api文檔。但在實際開發中往往api文檔不能及時更新,帶來一些問題。swagger就是解決這個問題的。
2. swagger簡介:
swagger是一個可以用來生成、描述、調用rest風格的web服務。我們可以通過swagger-ui生成後臺代碼的api接口信息,並且當你改動後臺接口的時候,可以同步更新你的接口文檔。也可以通過在線的swagger-edit編輯器,利用yaml或者json配置文件生成接口文檔,並把生成的文檔轉化成後臺的java代碼。我們只需要在生成的代碼中寫具體的業務邏輯。具體更多的用法參考swagger官網
3. springboot整合swagger,生成後臺接口文檔
- 引入maven依賴
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>2.9.2</version>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>2.9.2</version>
</dependency>
- 創建一個swagger註冊類
@Component
@EnableSwagger2 // 開啓swagger自動配置
public class SwaggerConfigure {
// controller路徑
private final String basePackage = "com.honeybee.controller";
/**
* 配置接口掃描
* 1.RequestHandlerSelectors.basePackage(basePackage) 掃描具體路徑
* 2.RequestHandlerSelectors.any() 掃描所有接口
* 3.RequestHandlerSelectors.none() 不掃描接口
* 4.RequestHandlerSelectors.withMethodAnnotation() 通過方法上的註解掃描
* 5.RequestHandlerSelectors.withClassAnnotation() 通過類上的註解掃描
* @return Docket
*/
@Bean
public Docket docket() {
return new Docket(DocumentationType.SWAGGER_2)
.apiInfo(apiInfo()).select()
.apis(RequestHandlerSelectors.basePackage(basePackage))
// 配置path過濾規則
// PathSelectors.any()
// PathSelectors.none()
// PathSelectors.regex()
//.paths(PathSelectors.ant("/*"))
.build();
}
private ApiInfo apiInfo() {
// 接口聯繫人信息
Contact contact = new Contact("HXY", "", "[email protected]");
// 接口信息
return new ApiInfo("honeybee", "honeybee", "v1.0",
"http://localhost:8888", contact, "Honeybee 1.0",
"", new ArrayList<>());
}
}
- 啓動項目,訪問http://localhost:8888/swagger-ui.html#/,就可以看到生成的接口文檔,如圖所示
- 實體類代碼
@Data
@ApiModel(value = "客戶信息")
public class CustomerBean implements Serializable {
@ApiModelProperty(value = "商家Id", required = true)
private String userId;
@ApiModelProperty(value = "顧客Id", required = true)
private String customerId;
@ApiModelProperty(value = "顧客姓名", required = true)
private String customerName;
@ApiModelProperty(value = "顧客電話", required = true)
private String customerPhone;
@ApiModelProperty(value = "顧客充值總金額", required = true)
private double totalMoney;
@ApiModelProperty(value = "創建時間")
private Date createTime;
@ApiModelProperty(value = "更新時間")
private Date updateTime;
}