之前的文章介紹了《推薦一款接口 API 設計神器!》,今天棧長給大家介紹下如何與優秀的 Spring Boot 框架進行集成,簡直不能太簡單。
你所需具備的基礎
- 告訴你,Spring Boot 真是個牛逼貨!
- Spring Boot 核心配置文件詳解
- Spring Boot 開啟的 2 種方式
- Spring Boot 自動配置原理、實戰
- Spring Boot 2.x 啟動全過程源碼分析
更多請在Java技術棧微信公眾號后台回復關鍵字:boot。
Spring Boot 集成 Swagger
1、添加依賴
Maven依賴示例:
<!-- Swagger -->
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
</dependency>
2、在 Spring Boot 配置文件中添加配置參數。
swagger:
title: API標題
description: API描述
version: 1.0
terms-of-service-url: http://www.javastack.cn/
base-package: cn.javastack.test.web
contact:
name: Javastack
url: http://www.javastack.cn/
email: admin@javastack.cn
3、添加配置類
@Getter
@Setter
@Configuration
@EnableSwagger2
@ConditionalOnClass(EnableSwagger2.class)
@ConfigurationProperties(prefix = "swagger")
public class SwaggerConfig {
/**
* API接口包路徑
*/
private String basePackage;
/**
* API頁面標題
*/
private String title;
/**
* API描述
*/
private String description;
/**
* 服務條款地址
*/
private String termsOfServiceUrl;
/**
* 版本號
*/
private String version;
/**
* 聯系人
*/
private Contact contact;
@Bean
public Docket api() {
return new Docket(DocumentationType.SWAGGER_2)
.apiInfo(apiInfo())
.select()
.apis(RequestHandlerSelectors.basePackage(basePackage))
.paths(PathSelectors.any())
.build();
}
private ApiInfo apiInfo() {
return new ApiInfoBuilder()
.title(title)
.description(description)
.termsOfServiceUrl(termsOfServiceUrl)
.version(version)
.contact(contact)
.build();
}
}
如何使用
Swagger 默認會根據配置的包,掃描所有接口並生成對應的 API 描述和參數信息,但這樣不是很直觀,需要對每個接口和參數進行自定義描述。
常用的 Swagger 注解如下。
注解名稱 | 使用說明 |
---|---|
@Api | 描述一個 API 類 |
@ApiImplicitParam | 描述一個請求參數 |
@ApiImplicitParams | 描述一組請求參數 |
@ApiModel | 描述一個返回的對象 |
@ApiModelProperty | 描述一個返回的對象參數 |
@ApiOperation | 描述一個 API 方法 |
@ApiParam | 描述一個方法的參數 |
@ApiResponse | 描述一個請求響應 |
@ApiResponses | 描述一組請求響應 |
使用示例如:
@Api(description = "登錄模塊")
@RestController
public class LoginController {
@ApiOperation(value = "登錄", httpMethod = "POST")
@ApiImplicitParams({
@ApiImplicitParam(name = "username", value = "用戶名", dataType = "string", paramType = "query"),
@ApiImplicitParam(name = "password", value = "密碼", dataType = "string", paramType = "query")})
@PostMapping(value = "/login")
public Object login(@RequestParam("username") String username, @RequestParam("password") String password) {
// ...
}
}
打開 swagger-ui 界面,可以看到所有的 API 接口定義,也可以在上面發起接口測試。
關注Java技術棧微信公眾號,在后台回復:工具,獲取棧長整理的更多的工具絕技,都是實戰干貨,以下僅為部分預覽。
- Java 開發必知道的國外 10 大網站
- 免費在線創作流程圖、思維導圖軟件
- 推薦一款代碼神器,代碼量至少省一半!
- 推薦一款接口 API 設計神器!
- 超詳細的 Git 實戰教程,傻瓜一看也會!
- ……
本文原創首發於微信公眾號:Java技術棧(id:javastack),關注公眾號在后台回復 "工具" 可獲取更多,轉載請原樣保留本信息。