SpringBoot Swagger 的使用
1.先說說Swagger的好處
- 整合到Spring Boot中,構建強大RESTful API文檔,並且使用簡單
- 省去接口文檔管理工作,修改代碼,自動更新
- Swagger2也提供了強大的頁面測試功能來調試RESTful API。
2.使用
swagger使用起來很簡單,只需要兩步就可以了。
- 添加pom依賴.
<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>
- 啓動類上添加@EnableSwagger2註解
@SpringBootApplication
@EnableJpaAuditing
@EnableSwagger2
public class TouristApplication {
public static void main(String[] args) {
SpringApplication.run(TouristApplication.class, args);
}
- 啓動項目,訪問路徑:http://localhost:8080/swagger-ui.html
- 啓動訪問效果
3.Swagger常用註解
- Api:修飾整個類,描述Controller的作用
- ApiOperation:描述一個類的一個方法,或者說一個接口
- ApiParam:單個參數描述
- ApiModel:用對象來接收參數
- ApiProperty:用對象接收參數時,描述對象的一個字段
- ApiResponse:HTTP響應其中1個描述
- ApiResponses:HTTP響應整體描述
- ApiIgnore:使用該註解忽略這個API
- ApiError :發生錯誤返回的信息
- ApiImplicitParam:一個請求參數
- ApiImplicitParams:多個請求參數
4.配置
在引入jar包正常啓動後, 已經可以正常使用Swagger, 各個屬性都提供了默認值, 當然如果需要自己設置一些屬性也可以, 配置方式如下
- yml 文件格式
swagger:
contact:
email: 聯繫郵箱
name: 聯繫人暱稱
url: 聯繫人地址
title: 標題
description: 描述
base-package: 接口所在包路徑
path-type: 接口選擇規則類型, 共分爲: ALL(所有接口), REGEX(符合正則), ANT(符合路徑)
- JavaBean格式
@Configuration
public class DemoConfig {
@Bean
public SwaggerBean swaggerBean() {
return SwaggerBean.builder()
.basePackage("com.xxx.xxx")
.pathType(PathType.ALL)
.title("標題")
.termsOfServiceUrl("http://127.0.0.1")
.license("XXXX")
.licenseUrl("http://xxx.xx.xx")
.description("描述")
.build();
}
}