SpringBoot3整合SpringDoc OpenAPI生成接口文檔的詳細過程
1、前言
在我們?nèi)粘i_發(fā)過程中,維護良好的 API 文檔對于團隊協(xié)作和開發(fā)效率至關(guān)重要。SpringDoc OpenAPI 是一個強大的工具,能夠幫助我們輕松生成 OpenAPI 3.0 規(guī)范的文檔,并提供交互式的 Swagger UI 界面。
本文跟著博主一起來學習如何在 Spring Boot 3 項目中整合 SpringDoc OpenAPI,生成在線接口文檔
2、SpringDoc OpenAPI版本介紹
目前 SpringDoc OpenAPI 有兩個版本 1.x 以及 2.x , 以下是版本對應(yīng)的支持:
Springdoc OpenAPI 1.x:支持 JDK 8 及以上版本(Spring Boot 2.x and 1.x.)
Springdoc OpenAPI 2.x:最新版本要求 JDK 11 及以上(Spring Boot 3.x)
下表描述了兩個版本主要模塊的更改:
| springdoc-openapi-v1 | springdoc-openapi-v2 | 描述 |
|---|---|---|
| springdoc-openapi-common | springdoc-openapi-starter-common | 包含基礎(chǔ)springdoc-openapi功能 |
| springdoc-openapi-data-rest | springdoc-openapi-starter-common | SpringData Rest 支持 |
| springdoc-openapi-groovy | springdoc-openapi-starter-common | Groovy支持 |
| springdoc-openapi-hateoas | springdoc-openapi-starter-common | Spring Hateoas 支持 |
| springdoc-openapi-javadoc | springdoc-openapi-starter-common | Javadoc支持 |
| springdoc-openapi-kotlin | springdoc-openapi-starter-common | kotlin支持 |
| springdoc-openapi-security | springdoc-openapi-starter-common | Spring Security支持 |
| springdoc-openapi-webmvc-core | springdoc-openapi-starter-webmvc-api | Spring WebMvc支持 |
| springdoc-openapi-webflux-core | springdoc-openapi-starter-webflux-api | Spring WebFlux支持 |
| springdoc-openapi-ui | springdoc-openapi-starter-webmvc-ui | 在Spring WebMvc上下文中使用Swagger-UI |
| springdoc-openapi-webflux-ui | springdoc-openapi-starter-webflux-ui | 在Spring WebFlux上下文中使用Swagger-UI |
確保你使用的 JDK 版本與 springdoc-openapi 的版本相匹配。如果你使用的是 Spring Boot 3,Springdoc OpenAPI 2.x 是推薦的版本,因為 Spring Boot 3 也要求 JDK 17 及以上
3、項目初始化
配置依賴
創(chuàng)建一個新的 Spring Boot 3 項目,這里博主選用的JDK版本為JDK17 ,Spring Boot: 3.0.0,在我們的在 pom.xml 文件中添加 Springdoc OpenAPI 的依賴
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!-- Springdoc OpenAPI Starter -->
<dependency>
<groupId>org.springdoc</groupId>
<artifactId>springdoc-openapi-starter-webmvc-ui</artifactId>
<version>2.5.0</version>
</dependency>
配置 Springdoc OpenAPI
springdoc-openapi 通過自動配置大多數(shù)情況下無需額外配置,但如果小伙伴有特定需求,可以在 application.yml 文件中添加配置,如:
springdoc:
api-docs:
enabled: true #
path: /api-docs # 默認/v3/api-docs
swagger-ui:
path: /swagger-ui.html #自定義swagger-ui HTML文檔路徑
編寫 REST Controller
創(chuàng)建一個簡單的 REST 控制器,并使用 OpenAPI 注解來描述 API
定義User對象
首先,我們?yōu)?User 類的字段添加注解說明
/**
* description 字段描述
* example 字段返回示例
**/
@Data
public class User {
@Schema(description = "用戶ID", example = "1")
private Long id;
@Schema(description = "用戶姓名", example = "張三")
private String name;
@Schema(description = "用戶郵箱", example = "zhansan@qq.com")
private String email;
}
創(chuàng)建一個簡單的 REST Controller,并使用 OpenAPI 注解來描述 API
import com.toher.springdoc.bean.User;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.media.Content;
import io.swagger.v3.oas.annotations.media.Schema;
import io.swagger.v3.oas.annotations.responses.ApiResponse;
import io.swagger.v3.oas.annotations.responses.ApiResponses;
import org.springframework.web.bind.annotation.*;
/**
* @Author 麥可樂
* @Date 2024/6/20 11:17 AM
* @Version 1.0
*/
@RestController
@RequestMapping("/api/users")
public class UserController {
@Operation(summary = "獲取用戶信息接口", description = "通過用戶ID獲取用戶信息")
@ApiResponses(value = {
@ApiResponse(responseCode = "200", description = "用戶信息",
content = {@Content(mediaType = "application/json",
schema = @Schema(implementation = User.class))}),
@ApiResponse(responseCode = "404", description = "無法獲取用戶信息")
})
@GetMapping("/{id}")
public User getUserById(@Parameter(description = "用戶ID") @PathVariable Long id) {
//模擬數(shù)據(jù)庫獲取用戶
User user = new User();
user.setId(1L);
user.setName("張三");
user.setEmail("zhansan@qq.com");
return user;
}
@Operation(summary = "創(chuàng)建用戶接口", description = "創(chuàng)建一個新用戶并返回帶有用戶id的User對象")
@ApiResponses(value = {
@ApiResponse(responseCode = "200", description = "用戶創(chuàng)建",
content = {@Content(mediaType = "application/json",
schema = @Schema(implementation = User.class))})
})
@PostMapping
public User createUser(@RequestBody User user) {
//模擬數(shù)據(jù)庫保存用戶并返回用戶ID主鍵
user.setId(1L);
return user;
}
}
測試查看文檔
最后啟動項目訪問查看文檔 http://localhost:端口號/swagger-ui,小伙伴應(yīng)該能夠看到自動生成的 API 文檔,并可以在界面中進行 API 測試,如下圖:

4、如何進行文檔分組
很多時候我們的接口很多,且可能不同的開發(fā)人員分配不同的模塊,如果所有接口都集中在一起,很明顯不利于我們查閱,這里博主介紹一下如何對文檔進行分組。
需要實用一個配置 group-configs, 如博主的配置
springdoc:
api-docs:
enabled: true #
path: /api-docs # 默認/v3/api-docs
swagger-ui:
path: /swagger-ui.html
group-configs: #進行文檔分組每個組配置對應(yīng)的請求路徑以及區(qū)分所在包
- group: 'user'
paths-to-match: '/api/users/**'
packages-to-scan: com.toher.springdoc.user
- group: 'product'
paths-to-match: '/api/product/**'
packages-to-scan: com.toher.springdoc.product
繼續(xù)測試訪問文檔,右上角 Select a definition 查看是否已經(jīng)分組

5、更換接口文檔UI
相信很多小伙伴還是不喜歡swagger-ui的文檔,這里博主介紹一個集 Swagger2 和 OpenAPI3 為一體的增強解決方案 - Knife4j
要使用 Knife4j 非常簡單,只需要引入依賴即可
<dependency>
<groupId>com.github.xiaoymin</groupId>
<artifactId>knife4j-openapi3-jakarta-spring-boot-starter</artifactId>
<version>4.4.0</version>
</dependency>
如果你希望開啟 Knife4j 的增強,可以在yml配置文件中追加,具體Knife4j增強配置明細,可以查看官方文檔 https://doc.xiaominfo.com/docs/features/enhance 這里就不贅述了
# knife4j的增強配置,不需要增強可以不配
knife4j:
enable: true
setting:
language: zh_cn
重啟我們的 SpringBoot 應(yīng)用訪問 http://localhost:端口號/doc.html 查看

6、字段必填如何設(shè)置
相信很多小伙伴在SpringBoot2的時候?qū)τ谖臋n中一些字段的要求,如:必填,我們可以使用一個注解屬性 required = true 來說明
@Schema(description = "用戶姓名", example = "張三" , required = true)
private String name;
但實際上在最新版本的 Springdoc OpenAPI 中,@Schema 注解的 required 屬性已經(jīng)被標記為過時。取而代之的是將字段的非空校驗放在參數(shù)或方法級別的注解上,結(jié)合 jakarta.validation
在 Springdoc OpenAPI 3 中,你可以使用 @Parameter 和 @RequestBody 注解來指定字段是否必需,同時在 @Schema 注解中可以通過指定非空屬性
下面我們來改造一下我們之前的代碼
User對象
import io.swagger.v3.oas.annotations.media.Schema;
import jakarta.validation.constraints.Email;
import jakarta.validation.constraints.NotNull;
import lombok.Data;
@Data
public class User {
@Schema(description = "用戶ID", example = "1")
private Long id;
@Schema(description = "用戶姓名", example = "張三")
@NotNull(message = "Name必填")
private String name;
@Schema(description = "用戶郵箱", example = "zhansan@qq.com")
@NotNull(message = "Email必填")
@Email(message = "郵箱格式不正確")
private String email;
}
UserController
import com.toher.springdoc.user.bean.User;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.media.Content;
import io.swagger.v3.oas.annotations.media.Schema;
import io.swagger.v3.oas.annotations.responses.ApiResponse;
import io.swagger.v3.oas.annotations.responses.ApiResponses;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.validation.Valid;
import org.springframework.web.bind.annotation.*;
@RestController
@RequestMapping("/api/users")
@Tag(name = "用戶接口")
public class UserController {
@Operation(summary = "獲取用戶信息接口", description = "通過用戶ID獲取用戶信息")
@ApiResponses(value = {
@ApiResponse(responseCode = "200", description = "用戶信息",
content = {@Content(mediaType = "application/json",
schema = @Schema(implementation = User.class))}),
@ApiResponse(responseCode = "404", description = "無法獲取用戶信息")
})
@GetMapping("/{id}")
public User getUserById(@Parameter(description = "用戶ID") @PathVariable Long id) {
//模擬數(shù)據(jù)庫獲取用戶
User user = new User();
user.setId(1L);
user.setName("張三");
user.setEmail("zhansan@qq.com");
return user;
}
@Operation(summary = "創(chuàng)建用戶接口", description = "創(chuàng)建一個新用戶并返回帶有用戶id的User對象")
@ApiResponses(value = {
@ApiResponse(responseCode = "200", description = "用戶創(chuàng)建",
content = {@Content(mediaType = "application/json",
schema = @Schema(implementation = User.class))})
})
@PostMapping
public User createUser(@Valid @RequestBody User user) {
//模擬數(shù)據(jù)庫保存用戶并返回用戶ID主鍵
user.setId(1L);
return user;
}
}
OK,我們還是重啟應(yīng)用觀察文檔說明。是否必填項上已經(jīng)顯示必填

7、結(jié)語
通過整合 Spring Boot 3 和 Springdoc OpenAPI,可以非常方便地生成交互式的在線 API 文檔,幫助開發(fā)者和使用者理解和測試 API。這不僅提高了開發(fā)效率,還能保證文檔的及時更新,保持與實際代碼的一致性。
以上就是SpringBoot3整合SpringDoc OpenAPI生成接口文檔的詳細過程的詳細內(nèi)容,更多關(guān)于SpringBoot3整合SpringDoc OpenAPI的資料請關(guān)注腳本之家其它相關(guān)文章!
- 關(guān)于springboot忽略接口,參數(shù)注解的使用ApiIgnore
- Springboot+Redis實現(xiàn)API接口防刷限流的項目實踐
- SpringBoot?快速實現(xiàn)?api?接口加解密功能
- 詳解Springboot快速搭建跨域API接口的步驟(idea社區(qū)版2023.1.4+apache-maven-3.9.3-bin)
- SpringBoot整合Sa-Token實現(xiàn)?API?接口簽名安全校驗功能
- SpringBoot如何根據(jù)目錄結(jié)構(gòu)生成API接口前綴
- SpringBoot可視化接口開發(fā)工具magic-api的簡單使用教程
- SpringBoot實現(xiàn)API接口的完整代碼
- springboot接入方式對接股票數(shù)據(jù)源API接口的操作方法
相關(guān)文章
RestTemplate在Spring或非Spring環(huán)境下使用精講
這篇文章主要為大家介紹了RestTemplate在Spring或非Spring環(huán)境下使用精講,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪2022-03-03
JDBC插入數(shù)據(jù)返回數(shù)據(jù)主鍵代碼實例
這篇文章主要介紹了JDBC插入數(shù)據(jù)返回數(shù)據(jù)主鍵代碼實例,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友可以參考下2020-11-11
Java利用Spire.Doc實現(xiàn)XML轉(zhuǎn)PDF的實戰(zhàn)指南
本文介紹了使用Spire.DocforJava將XML轉(zhuǎn)換為PDF的過程,首先說明了XML和PDF的應(yīng)用場景,然后通過Maven引入依賴,核心代碼展示了加載XML并轉(zhuǎn)換為PDF的方法,最后討論了進階設(shè)置、注意事項及常見問題,幫助開發(fā)者更好地完成轉(zhuǎn)換任務(wù),需要的朋友可以參考下2026-04-04

