整體概述
Spring Boot 是用于簡化 Spring 應用開發的框架,通過自動配置和約定大于配置原則,能讓開發者快速搭建和運行 Spring 應用。Knife4j 是基于 Swagger 增強的 API 文檔生成工具,可方便展示和調試 API 接口,生成美觀易用的 API 文檔。以下將詳細介紹如何從零開始把 Spring Boot 3.3.0 與 Knife4j 4.5.0 進行整合。
步驟 1:創建 Spring Boot 項目
方式一:使用 Spring Initializr
Spring Initializr 是在線的 Spring Boot 項目生成器,提供圖形化界面,便于快速創建項目。
- 打開瀏覽器,訪問?Spring Initializr。
- 在頁面做如下配置:
- Project:選?
Maven Project
,Maven 是項目管理和構建工具,可管理項目依賴、編譯、打包等操作。 - Language:選?
Java
,使用 Java 語言開發。 - Spring Boot:選?
3.3.0
,即要使用的 Spring Boot 版本。 - Group:通常是公司或組織域名倒序,如?
com.example
,用于唯一標識項目所屬組織或團隊。 - Artifact:是項目名稱,如?
spring - boot - knife4j - demo
,是項目在 Maven 倉庫的唯一標識符。 - Dependencies:點擊?
Add Dependencies
?按鈕,搜索并添加?Spring Web
?依賴,Spring Web
?用于開發 Web 應用,包含 Spring MVC 等核心組件。
- Project:選?
- 配置完成后,點擊?
Generate
?按鈕,瀏覽器會下載項目壓縮包。 - 解壓下載的壓縮包,用喜歡的集成開發環境(IDE)打開項目。以 IntelliJ IDEA 為例,打開 IDE,選?
File
?->?Open
,再選解壓后的項目文件夾。
方式二:使用 IDE 自帶的 Spring Initializr
若使用 IntelliJ IDEA,也可通過其自帶的 Spring Initializr 創建項目:
- 打開 IntelliJ IDEA,選?
File
?->?New
?->?Project
。 - 在左側面板選?
Spring Initializr
,按上述步驟 2 配置。 - 點擊?
Next
,選項目存儲位置,再點擊?Finish
?完成項目創建。
步驟 2:添加 Knife4j 依賴
在項目的?pom.xml
?文件中添加 Knife4j 依賴。pom.xml
?是 Maven 項目配置文件,用于管理項目依賴和構建信息。打開?pom.xml
?文件,在?<dependencies>
?標簽內添加以下代碼:
<dependencies><!-- Spring Web 依賴,用于開發 Web 應用 --><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-web</artifactId></dependency><!-- Knife4j 依賴,用于生成和展示 API 文檔 --><dependency><groupId>com.github.xiaoymin</groupId><artifactId>knife4j-openapi3-jakarta-spring-boot-starter</artifactId><version>4.5.0</version></dependency>
</dependencies>
添加依賴后,Maven 會自動從中央倉庫下載所需庫文件。在 IntelliJ IDEA 中,IDE 會自動檢測?pom.xml
?文件變化,并提示導入依賴,點擊?Import Changes
?按鈕,等待依賴下載完成。
步驟 3:?Knife4j 界面自定義配置
package org.example.test1;import org.springdoc.core.models.GroupedOpenApi;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;@Configuration
public class Knife4jConfig {@Beanpublic GroupedOpenApi api4() {return GroupedOpenApi.builder().group("all").displayName("所有接口").packagesToScan("org.example.test1")// 自定義全局響應碼
// .addOpenApiCustomizer((this::setCustomStatusCode)).build();}
}
步驟 4:創建實體類
實體類用于表示業務數據,使用 Swagger 注解為實體類和其屬性添加描述信息,以便在 API 文檔中清晰展示。
@Schema 注解用于為實體類添加描述信息,name 為實體類在文檔中的名稱,description 為詳細描述
?@Schema 注解為屬性添加描述信息,description 為屬性描述,example 為示例值
import io.swagger.v3.oas.annotations.media.Schema;// @Schema 注解用于為實體類添加描述信息,name 為實體類在文檔中的名稱,description 為詳細描述
@Schema(name = "User", description = "用戶實體類")
public class User {// @Schema 注解為屬性添加描述信息,description 為屬性描述,example 為示例值@Schema(description = "用戶 ID", example = "1")private Long id;@Schema(description = "用戶名", example = "張三")private String username;@Schema(description = "用戶郵箱", example = "666@example.com")private String email;// 構造函數、Getter 和 Setter 方法public User() {}public User(Long id, String username, String email) {this.id = id;this.username = username;this.email = email;}public Long getId() {return id;}public void setId(Long id) {this.id = id;}public String getUsername() {return username;}public void setUsername(String username) {this.username = username;}public String getEmail() {return email;}public void setEmail(String email) {this.email = email;}
}
步驟 5:創建 Controller
Controller 負責處理客戶端請求并返回響應。使用更多 Swagger 注解描述接口的請求參數、響應結果等信息。
// @Tag 用于對 API 接口進行分組和描述,name 為分組名稱,description 為分組詳細描述
?// @Operation 描述接口的操作信息,summary 為摘要,description 為詳細描述
?// @ApiResponses 定義接口的響應狀態碼和對應的響應信息
import io.swagger.v3.oas.annotations.Operation; // 導入Swagger Operation注解,用于描述API操作
import io.swagger.v3.oas.annotations.Parameter; // 導入Swagger Parameter注解,用于描述API參數
import io.swagger.v3.oas.annotations.media.Content; // 導入Swagger Content注解,用于定義API響應內容類型
import io.swagger.v3.oas.annotations.media.Schema; // 導入Swagger Schema注解,用于定義API響應模式
import io.swagger.v3.oas.annotations.responses.ApiResponse; // 導入Swagger ApiResponse注解,用于定義API響應信息
import io.swagger.v3.oas.annotations.responses.ApiResponses; // 導入Swagger ApiResponses注解,用于定義多個API響應信息
import io.swagger.v3.oas.annotations.tags.Tag; // 導入Swagger Tag注解,用于對API進行分組和描述
import org.springframework.web.bind.annotation.*; // 導入Spring MVC注解,用于處理HTTP請求import java.util.ArrayList; // 導入ArrayList類,用于動態數組操作
import java.util.List; // 導入List接口// @RestController 是 @Controller 和 @ResponseBody 的組合注解,標識該類是RESTful風格的控制器
@RestController
// @RequestMapping 用于映射請求的URL前綴
@RequestMapping("/api/users")
// @Tag 用于對API接口進行分組和描述,name 為分組名稱,description 為分組詳細描述
@Tag(name = "用戶管理接口", description = "提供用戶相關的操作接口")
public class UserController {private List<User> users = new ArrayList<>(); // 創建一個List集合用于存儲用戶數據// @Operation 描述接口的操作信息,summary 為摘要,description 為詳細描述@Operation(summary = "獲取所有用戶", description = "返回所有用戶的列表")// @ApiResponses 定義接口的響應狀態碼和對應的響應信息@ApiResponses(value = {// @ApiResponse 具體描述某個響應狀態碼的信息,responseCode 為響應狀態碼,description 為描述,content 為響應內容@ApiResponse(responseCode = "200", description = "成功獲取用戶列表",content = {@Content(mediaType = "application/json",// @Schema 指定響應內容的數據結構schema = @Schema(implementation = User.class))}})})@GetMappingpublic List<User> getUsers() { // 定義一個GET請求處理方法,返回用戶列表return users; // 返回用戶列表}@Operation(summary = "根據 ID 獲取用戶", description = "根據用戶 ID 獲取單個用戶信息")@ApiResponses(value = {@ApiResponse(responseCode = "200", description = "成功獲取用戶信息",content = {@Content(mediaType = "application/json",schema = @Schema(implementation = User.class))}),@ApiResponse(responseCode = "404", description = "未找到該用戶", content = @Content)})// @Parameter 描述接口的請求參數,description 為參數描述,example 為示例值@GetMapping("/{id}")public User getUserById(@Parameter(description = "用戶 ID", example = "1") @PathVariable Long id) { // 定義一個GET請求處理方法,根據ID獲取用戶信息return users.stream() // 將用戶列表轉換為流.filter(user -> user.getId().equals(id)) // 過濾出ID匹配的用戶.findFirst() // 查找第一個匹配的用戶.orElse(null); // 如果沒有找到,返回null}@Operation(summary = "創建用戶", description = "創建一個新的用戶")@ApiResponses(value = {@ApiResponse(responseCode = "201", description = "用戶創建成功",content = {@Content(mediaType = "application/json",schema = @Schema(implementation = User.class))}})@PostMappingpublic User createUser(@Parameter(description = "用戶信息", required = true) @RequestBody User user) { // 定義一個POST請求處理方法,創建新用戶users.add(user); // 將新用戶添加到列表return user; // 返回創建的用戶}@Operation(summary = "獲取所有用戶2", description = "返回所有用戶的列表")@ApiResponses(value = {@ApiResponse(responseCode = "200", description = "成功獲取用戶列表",content = {@Content(mediaType = "application/json",schema = @Schema(implementation = User.class))}})@GetMappingpublic List<User> getUsers2(@Parameter(name = "X-Token", description = "自定義請求頭 token", in = ParameterIn.HEADER) @RequestHeader(required = false) String token) { // 定義一個GET請求處理方法,返回用戶列表,支持自定義請求頭參數return users; // 返回用戶列表}}
步驟 6:啟動 Spring Boot 應用
在 IDE 中找到項目的啟動類(通常是包含?main
?方法且帶有?@SpringBootApplication
?注解的類),右鍵點擊并選擇?Run
?啟動 Spring Boot 應用。啟動成功后,控制臺會輸出啟動信息,表明應用已在默認端口(通常是 8080)啟動。
步驟 7:訪問 Knife4j 文檔頁面
打開瀏覽器,訪問以下 URL 查看 Knife4j 生成的 API 文檔:http://localhost:8080/doc.html
在Springboot的yml文件中配置Knife4j ?
# Knife4j配置
# springdoc-openapi配置
springdoc:# get請求多參數時不需要添加額外的@ParameterObject和@Parameter注解default-flat-param-object: true# 啟用swaggerUIswagger-ui:#自定義swagger前端請求路徑,輸入http:127.0.0.1:8080/swagger-ui.html會自動重定向到swagger頁面path: /swagger-ui.htmlenabled: true# tags-sorter: alpha # 標簽的排序方式 alpha:按照子母順序排序(@ApiSupport注解排序不生效,因此需要設置)# operations-sorter: alpha # 接口的排序方式 alpha:按照子母順序排序(@ApiOperationSupport注解排序生效,因此這里不作設置)operations-sorter: order # 設置規則為order,該規則會使用Knife4j的增強排序擴展規則`x-order`# 啟用文檔,默認開啟api-docs:path: /v3/api-docs #swagger后端請求地址enabled: true
# knife4j相關配置 可以不用改
knife4j:enable: true #開啟knife4j,無需添加@EnableKnife4j注解setting:language: ZH_CN # 中文:ZH_CN 英文:ENenable-swagger-models: trueenable-dynamic-parameter: falsefooter-custom-content: "<strong>Copyright ?? 2024 Keyidea. All Rights Reversed</strong>"enable-footer-custom: trueenable-footer: trueenable-document-manage: truedocuments: #文檔補充說明- name: MarkDown語法說明locations: classpath:static/markdown/grammar/*group: 01-系統接口 # 此處分組必須使用在Knife4jConfig已存在的分組名group,當存在displayName時,使用displayName名稱- name: 補充文檔locations: classpath:static/markdown/others/*group: 01-系統接口 # 此處分組必須使用在Knife4jConfig已存在的分組名group,當存在displayName時,使用displayName名稱