SpringBoot3整合SpringDoc OpenAPI生成接口文檔的詳細(xì)過程
1、前言
在我們?nèi)粘i_發(fā)過程中,維護(hù)良好的 API
文檔對于團(tuán)隊(duì)協(xié)作和開發(fā)效率至關(guān)重要。SpringDoc OpenAPI
是一個(gè)強(qiáng)大的工具,能夠幫助我們輕松生成 OpenAPI 3.0
規(guī)范的文檔,并提供交互式的 Swagger UI
界面。
本文跟著博主一起來學(xué)習(xí)如何在 Spring Boot 3
項(xiàng)目中整合 SpringDoc OpenAPI
,生成在線接口文檔
2、SpringDoc OpenAPI版本介紹
目前 SpringDoc OpenAPI
有兩個(gè)版本 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)
下表描述了兩個(gè)版本主要模塊的更改:
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
是推薦的版本,因?yàn)?Spring Boot 3
也要求 JDK 17 及以上
3、項(xiàng)目初始化
配置依賴
創(chuàng)建一個(gè)新的 Spring Boot 3 項(xiàng)目,這里博主選用的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
通過自動(dòng)配置大多數(shù)情況下無需額外配置,但如果小伙伴有特定需求,可以在 application.yml 文件中添加配置,如:
springdoc: api-docs: enabled: true # path: /api-docs # 默認(rèn)/v3/api-docs swagger-ui: path: /swagger-ui.html #自定義swagger-ui HTML文檔路徑
編寫 REST Controller
創(chuàng)建一個(gè)簡單的 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)建一個(gè)簡單的 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)建一個(gè)新用戶并返回帶有用戶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; } }
測試查看文檔
最后啟動(dòng)項(xiàng)目訪問查看文檔 http://localhost:端口號/swagger-ui
,小伙伴應(yīng)該能夠看到自動(dòng)生成的 API 文檔,并可以在界面中進(jìn)行 API 測試,如下圖:
4、如何進(jìn)行文檔分組
很多時(shí)候我們的接口很多,且可能不同的開發(fā)人員分配不同的模塊,如果所有接口都集中在一起,很明顯不利于我們查閱,這里博主介紹一下如何對文檔進(jìn)行分組。
需要實(shí)用一個(gè)配置 group-configs
, 如博主的配置
springdoc: api-docs: enabled: true # path: /api-docs # 默認(rèn)/v3/api-docs swagger-ui: path: /swagger-ui.html group-configs: #進(jìn)行文檔分組每個(gè)組配置對應(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的文檔,這里博主介紹一個(gè)集 Swagger2
和 OpenAPI3
為一體的增強(qiáng)解決方案 - Knife4j
要使用 Knife4j
非常簡單,只需要引入依賴即可
<dependency> <groupId>com.github.xiaoymin</groupId> <artifactId>knife4j-openapi3-jakarta-spring-boot-starter</artifactId> <version>4.4.0</version> </dependency>
如果你希望開啟 Knife4j
的增強(qiáng),可以在yml配置文件中追加,具體Knife4j
增強(qiáng)配置明細(xì),可以查看官方文檔 https://doc.xiaominfo.com/docs/features/enhance 這里就不贅述了
# knife4j的增強(qiáng)配置,不需要增強(qiáng)可以不配 knife4j: enable: true setting: language: zh_cn
重啟我們的 SpringBoot
應(yīng)用訪問 http://localhost:端口號/doc.html
查看
6、字段必填如何設(shè)置
相信很多小伙伴在SpringBoot2的時(shí)候?qū)τ谖臋n中一些字段的要求,如:必填,我們可以使用一個(gè)注解屬性 required = true
來說明
@Schema(description = "用戶姓名", example = "張三" , required = true) private String name;
但實(shí)際上在最新版本的 Springdoc OpenAPI
中,@Schema
注解的 required
屬性已經(jīng)被標(biāo)記為過時(shí)
。取而代之的是將字段的非空校驗(yàn)放在參數(shù)或方法級別的注解上,結(jié)合 jakarta.validation
在 Springdoc OpenAPI 3
中,你可以使用 @Parameter
和 @RequestBody
注解來指定字段是否必需,同時(shí)在 @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)建一個(gè)新用戶并返回帶有用戶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)用觀察文檔說明。是否必填項(xiàng)上已經(jīng)顯示必填
7、結(jié)語
通過整合 Spring Boot 3 和 Springdoc OpenAPI,可以非常方便地生成交互式的在線 API 文檔,幫助開發(fā)者和使用者理解和測試 API。這不僅提高了開發(fā)效率,還能保證文檔的及時(shí)更新,保持與實(shí)際代碼的一致性。
以上就是SpringBoot3整合SpringDoc OpenAPI生成接口文檔的詳細(xì)過程的詳細(xì)內(nèi)容,更多關(guān)于SpringBoot3整合SpringDoc OpenAPI的資料請關(guān)注腳本之家其它相關(guān)文章!
- 關(guān)于springboot忽略接口,參數(shù)注解的使用ApiIgnore
- Springboot+Redis實(shí)現(xiàn)API接口防刷限流的項(xiàng)目實(shí)踐
- SpringBoot?快速實(shí)現(xiàn)?api?接口加解密功能
- 詳解Springboot快速搭建跨域API接口的步驟(idea社區(qū)版2023.1.4+apache-maven-3.9.3-bin)
- SpringBoot整合Sa-Token實(shí)現(xiàn)?API?接口簽名安全校驗(yàn)功能
- SpringBoot如何根據(jù)目錄結(jié)構(gòu)生成API接口前綴
- SpringBoot可視化接口開發(fā)工具magic-api的簡單使用教程
- SpringBoot實(shí)現(xiàn)API接口的完整代碼
- springboot接入方式對接股票數(shù)據(jù)源API接口的操作方法
相關(guān)文章
Springboot集成第三方j(luò)ar快速實(shí)現(xiàn)微信、支付寶等支付場景
這篇文章主要介紹了Springboot集成第三方j(luò)ar快速實(shí)現(xiàn)微信、支付寶等支付場景,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2021-01-01解決MyEclipse出現(xiàn)the user operation is waiting的問題
今天做項(xiàng)目的時(shí)候每次修改代碼保存后都會(huì)跳出一個(gè)框框,然后就有兩個(gè)進(jìn)度條,上面寫the user operation is wating...小編去網(wǎng)上查了查解決了這個(gè)問題,下面跟大家分享一下。2018-04-04Java多態(tài)實(shí)現(xiàn)原理詳細(xì)梳理總結(jié)
這篇文章主要介紹了Java多態(tài)實(shí)現(xiàn)原理詳細(xì)梳理總結(jié),多態(tài)是繼封裝、繼承之后,面向?qū)ο蟮牡谌筇匦裕疚闹豢偨Y(jié)了多態(tài)的實(shí)現(xiàn)原理,需要的朋友可以參考一下2022-06-06Java使用Collections工具類對List集合進(jìn)行排序
這篇文章主要介紹了Java使用Collections工具類對List集合進(jìn)行排序,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下2019-10-10