Spring Boot Swagger3 使用方法及核心配置
Swagger3(OpenAPI 3.0)作為 API 文檔生成工具,能幫助開發(fā)者快速構建清晰、可交互的 API 文檔,減少前后端協(xié)作溝通成本。本文基于 springdoc-openapi 實現(xiàn),詳細介紹 Swagger3 在 Spring Boot 項目中的基本使用方法、核心配置、常用注解及進階優(yōu)化方案。
一、項目環(huán)境與依賴配置
1. 環(huán)境要求
- Spring Boot 版本:2.7.x 及以上(兼容 Spring Boot 3.x)
- JDK 版本:1.8 及以上
2. 添加核心依賴
在項目 pom.xml 中引入 Swagger3 核心依賴(springdoc-openapi 實現(xiàn))和 Knife4j 增強 UI 依賴(提供更友好的交互體驗):
<!-- Swagger3 核心依賴(SpringDoc 實現(xiàn)) -->
<dependency>
<groupId>org.springdoc</groupId>
<artifactId>springdoc-openapi-starter-webmvc-ui</artifactId>
<version>2.5.0</version> <!-- 穩(wěn)定版本,與 Spring Boot 版本兼容 -->
</dependency>
<!-- Knife4j 增強 UI(推薦,提供更友好的交互) -->
<dependency>
<groupId>com.github.xiaoymin</groupId>
<artifactId>knife4j-openapi3-jakarta-spring-boot-starter</artifactId>
<version>4.5.0</version>
</dependency>說明:若使用 Spring Boot 3.x,需確保依賴的
jakarta版本兼容,Knife4j 4.5.0+ 已適配 Spring Boot 3.x。
二、Swagger3 核心配置
1. 配置類編寫
創(chuàng)建 Swagger 配置類,定義 API 基本信息、安全方案、服務器環(huán)境等核心配置:
import io.swagger.v3.oas.models.OpenAPI;
import io.swagger.v3.oas.models.info.Contact;
import io.swagger.v3.oas.models.info.Info;
import io.swagger.v3.oas.models.info.License;
import io.swagger.v3.oas.models.security.SecurityRequirement;
import io.swagger.v3.oas.models.security.SecurityScheme;
import io.swagger.v3.oas.models.servers.Server;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import java.util.Arrays;
@Configuration
public class SwaggerConfig {
@Bean
public OpenAPI customOpenAPI() {
return new OpenAPI()
// 1. API 基本信息配置
.info(new Info()
.title("Spring Boot Swagger3 Demo API") // 文檔標題
.version("1.0.0") // 接口版本
.description("這是一個 Spring Boot Swagger3 示例項目,展示了 Swagger3 的核心特性(注解使用、認證配置、多環(huán)境適配等)") // 文檔描述
.contact(new Contact() // 聯(lián)系人信息
.name("Example Team")
.email("contact@example.com")
.url("http://example.com")
)
.license(new License() // 許可證信息
.name("Apache 2.0")
.url("http://springdoc.org")
)
)
// 2. 安全方案配置(JWT Bearer 認證)
.addSecurityItem(new SecurityRequirement().addList("bearerAuth"))
.components(new io.swagger.v3.oas.models.Components()
.addSecuritySchemes("bearerAuth", new SecurityScheme()
.name("bearerAuth")
.type(SecurityScheme.Type.HTTP)
.scheme("bearer")
.bearerFormat("JWT")
)
)
// 3. 服務器環(huán)境配置(本地/測試/生產)
.servers(Arrays.asList(
new Server().url("http://localhost:8080").description("本地開發(fā)環(huán)境"),
new Server().url("https://staging.example.com").description("測試環(huán)境"),
new Server().url("https://production.example.com").description("生產環(huán)境")
));
}
}2. 多環(huán)境配置(application-{profile}.properties)
通過配置文件控制不同環(huán)境是否啟用 Swagger(生產環(huán)境建議禁用,避免接口暴露):
開發(fā)環(huán)境(application-dev.properties)
# 啟用 Swagger3 文檔 springdoc.swagger-ui.enabled=true springdoc.api-docs.enabled=true springdoc.openapi.enabled=true # Swagger UI 優(yōu)化配置 springdoc.swagger-ui.operations-sorter=alpha # 接口按字母排序(alpha=字母序,method=請求方法序) springdoc.swagger-ui.tags-sorter=alpha # 分組按字母排序 springdoc.swagger-ui.default-model-expand-depth=2 # 默認展開模型層級(2級) springdoc.swagger-ui.default-models-expand-depth=2 # 默認展開所有模型 springdoc.swagger-ui.path=/swagger-ui.html # 原生 Swagger UI 訪問路徑 knife4j.enable=true # 啟用 Knife4j 增強 UI
生產環(huán)境(application-prod.properties)
# 生產環(huán)境禁用 Swagger(安全考慮) springdoc.swagger-ui.enabled=false springdoc.api-docs.enabled=false springdoc.openapi.enabled=false knife4j.enable=false # 禁用 Knife4j UI
三、常用注解與實戰(zhàn)示例
Swagger3 通過注解描述 API 接口、參數、響應和數據模型,以下是核心注解的實戰(zhàn)用法(基于控制器和實體類):
1. 接口分組:@Tag
用于標記控制器或接口組,方便文檔分類展示,支持關聯(lián)外部文檔:
import io.swagger.v3.oas.annotations.tags.Tag;
import io.swagger.v3.oas.annotations.externalDocs.ExternalDocumentation;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping("/api/users")
@Tag(
name = "用戶管理", // 分組名稱(文檔中顯示的分組標簽)
description = "用戶相關核心接口,包含用戶查詢、創(chuàng)建、更新、刪除等 CRUD 操作", // 分組描述
externalDocs = @ExternalDocumentation( // 外部文檔鏈接(可選)
url = "http://example.com/docs/user-api",
description = "用戶管理 API 詳細設計文檔"
)
)
public class UserController {
// 接口實現(xiàn)...
}2. 接口描述:@Operation
用于描述具體接口的功能、用途,支持指定接口排序:
import io.swagger.v3.oas.annotations.Operation;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
@Operation(
summary = "分頁查詢所有用戶", // 接口簡要說明(文檔列表頁顯示)
description = "支持按頁碼和每頁大小分頁,返回用戶列表及分頁信息(總條數、總頁數)", // 詳細描述
tags = {"用戶管理"}, // 所屬分組(與 @Tag 名稱一致)
position = 1 // 接口排序權重(數值越小越靠前)
)
@GetMapping
public ResponseEntity<PageResponse> getAllUsers(
@RequestParam(defaultValue = "1") Integer page, // 頁碼(默認1)
@RequestParam(defaultValue = "10") Integer size // 每頁大小(默認10)
) {
// 業(yè)務邏輯:查詢分頁用戶數據
Page<User> userPage = userService.listUsers(page - 1, size); // page 從 0 開始
PageResponse pageResponse = new PageResponse<>(
userPage.getContent(),
userPage.getTotalElements(),
userPage.getTotalPages(),
page,
size
);
return ResponseEntity.ok(ApiResponse.success(pageResponse));
}3. 請求參數描述:@Parameter
用于描述請求參數(路徑參數、查詢參數、請求頭),明確參數含義、示例值和約束:
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.models.enums.ParameterIn;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
@Operation(summary = "根據 ID 查詢用戶", description = "通過用戶唯一 ID 獲取用戶詳情", position = 2)
@GetMapping("/{id}")
public ResponseEntity<ApiResponse> getUserById(
@Parameter(
description = "用戶唯一 ID", // 參數說明
example = "1001", // 示例值(文檔中可直接使用)
in = ParameterIn.PATH, // 參數位置:PATH/QUERY/HEADER
required = true, // 是否必填(默認 false)
name = "id" // 參數名稱(與 @PathVariable 一致)
)
@PathVariable Long id
) {
User user = userService.getUserById(id);
if (user == null) {
return ResponseEntity.ok(ApiResponse.fail("用戶不存在"));
}
return ResponseEntity.ok(ApiResponse.success(user));
}4. 響應說明:@ApiResponses + @ApiResponse
定義接口可能的響應狀態(tài)碼、描述和響應格式,幫助前端理解返回邏輯:
import io.swagger.v3.oas.annotations.responses.ApiResponse;
import io.swagger.v3.oas.annotations.responses.ApiResponses;
import io.swagger.v3.oas.annotations.media.Content;
import io.swagger.v3.oas.annotations.media.Schema;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
@Operation(summary = "創(chuàng)建用戶", description = "新增用戶信息,用戶名不可重復", position = 3)
@ApiResponses({
@ApiResponse(
responseCode = "201", // 響應狀態(tài)碼(創(chuàng)建成功)
description = "用戶創(chuàng)建成功",
content = @Content(
mediaType = "application/json",
schema = @Schema(implementation = ApiResponse.class) // 響應數據模型
)
),
@ApiResponse(responseCode = "400", description = "請求參數錯誤(如用戶名長度不足、郵箱格式錯誤)"),
@ApiResponse(responseCode = "409", description = "用戶名已存在(沖突)"),
@ApiResponse(responseCode = "500", description = "服務器內部錯誤")
})
@PostMapping
public ResponseEntity<ApiResponse> createUser(
@RequestBody User user // 請求體(下文詳細描述)
) {
boolean success = userService.createUser(user);
if (success) {
return ResponseEntity.status(201).body(ApiResponse.success(user));
}
return ResponseEntity.ok(ApiResponse.fail("創(chuàng)建失敗"));
}5. 請求體描述:@RequestBody
用于描述 POST/PUT 等請求的請求體,明確請求格式、示例值和必填項:
import io.swagger.v3.oas.annotations.parameters.RequestBody;
import io.swagger.v3.oas.annotations.media.ExampleObject;
@PostMapping
public ResponseEntity<ApiResponse> createUser(
@RequestBody(
description = "用戶創(chuàng)建請求參數",
required = true, // 是否必填
content = @Content(
mediaType = "application/json",
examples = @ExampleObject( // 請求體示例(文檔中可直接復制使用)
name = "創(chuàng)建用戶示例",
value = "{\"username\": \"test_user\", \"password\": \"123456a\", \"email\": \"test@example.com\", \"age\": 25, \"active\": true}"
),
schema = @Schema(implementation = User.class) // 請求體數據模型
)
)
@org.springframework.web.bind.annotation.RequestBody User user
) {
// 業(yè)務邏輯...
}6. 數據模型描述:@Schema
用于描述實體類及其字段,明確字段含義、示例值、數據格式和約束:
import io.swagger.v3.oas.annotations.media.Schema;
import lombok.Data;
@Data
@Schema(description = "用戶實體類(存儲用戶核心信息)")
public class User {
@Schema(
description = "用戶唯一 ID",
example = "1001",
accessMode = Schema.AccessMode.READ_ONLY // 只讀字段(創(chuàng)建時無需傳入)
)
private Long id;
@Schema(
description = "用戶名(登錄賬號)",
example = "admin",
requiredMode = Schema.RequiredMode.REQUIRED, // 必填字段
minLength = 3, // 最小長度
maxLength = 20, // 最大長度
pattern = "^[a-zA-Z0-9_]+$" // 正則表達式(僅允許字母、數字、下劃線)
)
private String username;
@Schema(
description = "用戶郵箱",
example = "admin@example.com",
format = "email", // 數據格式(郵箱格式校驗)
requiredMode = Schema.RequiredMode.REQUIRED
)
private String email;
@Schema(
description = "用戶年齡",
example = "28",
minimum = "1", // 最小值
maximum = "120", // 最大值
requiredMode = Schema.RequiredMode.NOT_REQUIRED // 非必填
)
private Integer age;
@Schema(
description = "賬號狀態(tài)(true=啟用,false=禁用)",
example = "true",
defaultValue = "true" // 默認值
)
private Boolean active;
}四、進階功能配置
1. 全局參數配置
若項目中所有接口都需要攜帶固定參數(如 X-Request-Id 請求頭),可在 SwaggerConfig 中添加全局參數:
import io.swagger.v3.oas.models.parameters.Parameter;
import io.swagger.v3.oas.models.media.Schema;
import java.util.Collections;
@Bean
public OpenAPI customOpenAPI() {
// 全局請求頭參數:X-Request-Id(用于鏈路追蹤)
Parameter globalRequestId = new Parameter()
.name("X-Request-Id")
.description("請求唯一標識(用于鏈路追蹤)")
.in(ParameterIn.HEADER)
.required(false)
.schema(new Schema().example("req-20240520123456"));
return new OpenAPI()
.info(...) // 原有信息配置
.addSecurityItem(...) // 原有安全配置
.components(...) // 原有組件配置
.servers(...) // 原有服務器配置
.addParametersItem(globalRequestId); // 添加全局參數
}2. 分組排序優(yōu)化
通過 extensions 配置分組排序,讓文檔分組更符合業(yè)務邏輯:
import java.util.Arrays;
import java.util.HashMap;
import java.util.Collections;
@Bean
public OpenAPI customOpenAPI() {
return new OpenAPI()
.info(...)
.addSecurityItem(...)
.components(...)
.servers(...)
// 分組排序配置
.extensions(Collections.singletonMap(
"x-tagGroups",
Arrays.asList(
new HashMap<String, Object>() {{
put("name", "核心業(yè)務");
put("tags", Arrays.asList("用戶管理", "訂單管理"));
put("order", 1); // 分組排序權重(數值越小越靠前)
}},
new HashMap<String, Object>() {{
put("name", "基礎功能");
put("tags", Arrays.asList("產品管理", "系統(tǒng)配置"));
put("order", 2);
}}
)
));
}3. 忽略指定接口、參數
- 忽略接口:使用
@Hidden注解(該接口不會顯示在文檔中)
import io.swagger.v3.oas.annotations.Hidden;
@Hidden
@GetMapping("/internal") // 內部接口,不對外暴露
public ResponseEntity() {
return ResponseEntity.ok("內部接口返回");
}
- 忽略參數:在
@Parameter中設置hidden = true
@GetMapping("/info")
public ResponseEntity<ApiResponse>(
@Parameter(hidden = true) // 隱藏該參數(不顯示在文檔中)
@RequestParam String secretKey // 內部校驗參數,無需前端關注
) {
// 業(yè)務邏輯...
}
4. 自定義響應示例(續(xù))
@ApiResponses({
@ApiResponse(
responseCode = "200",
description = "操作成功",
content = @Content(
mediaType = "application/json",
examples = @ExampleObject(
name = "成功示例",
value = "{\"code\": 200, \"message\": \"操作成功\", \"data\": {\"id\": 1001, \"username\": \"admin\", \"email\": \"admin@example.com\"}}"
)
)
),
@ApiResponse(
responseCode = "400",
description = "參數錯誤",
content = @Content(
mediaType = "application/json",
examples = @ExampleObject(
name = "參數錯誤示例",
value = "{\"code\": 400, \"message\": \"用戶名長度不能小于3位\", \"data\": null}"
)
)
)
})
@PostMapping
public ResponseEntity<ApiResponse> createUser(@RequestBody User user) {
// 業(yè)務邏輯...
}
5. 集成 Spring Security 權限控制
若項目使用 Spring Security 進行權限管理,可通過 Swagger 配置實現(xiàn)認證聯(lián)動,讓文檔支持攜帶令牌訪問受保護接口:
import io.swagger.v3.oas.models.security.OAuthFlow;
import io.swagger.v3.oas.models.security.OAuthFlows;
import io.swagger.v3.oas.models.security.Scopes;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class SwaggerConfig {
@Bean
public OpenAPI customOpenAPI() {
return new OpenAPI()
.info(...) // 原有信息配置
// 配置 OAuth2 認證(密碼模式)
.addSecurityItem(new SecurityRequirement().addList("oauth2"))
.components(new io.swagger.v3.oas.models.Components()
.addSecuritySchemes("oauth2", new SecurityScheme()
.type(SecurityScheme.Type.OAUTH2)
.flows(new OAuthFlows()
.password(new OAuthFlow()
.tokenUrl("http://localhost:8080/oauth2/token") // 令牌獲取地址
.scopes(new Scopes()
.addString("read", "讀取權限")
.addString("write", "寫入權限")
)
)
)
)
)
.servers(...); // 原有服務器配置
}
}
補充:需在 Spring Security 配置中放行 Swagger 相關路徑,避免被攔截:
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.web.SecurityFilterChain;
@Configuration
public class SecurityConfig {
@Bean
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
http.authorizeHttpRequests(auth -> auth
// 放行 Swagger 相關路徑
.requestMatchers("/swagger-ui/**", "/v3/api-docs/**", "/knife4j/**").permitAll()
.anyRequest().authenticated()
);
return http.build();
}
}
五、文檔訪問與調試
1. 訪問地址
配置完成后,啟動項目,通過以下地址訪問 Swagger 文檔:
- 原生 Swagger UI:
http://localhost:8080/swagger-ui.html - Knife4j 增強 UI(推薦):
http://localhost:8080/doc.html - OpenAPI 規(guī)范 JSON:
http://localhost:8080/v3/api-docs
2. 在線調試流程
- 打開 Knife4j UI 地址,在文檔頂部選擇對應的服務器環(huán)境(如本地開發(fā)環(huán)境);
- 若配置了認證(JWT/OAuth2),點擊頁面右上角「授權」按鈕,輸入令牌或完成認證流程;
- 選擇目標接口,點擊「調試」按鈕,填寫請求參數(路徑參數 / 查詢參數 / 請求體);
- 點擊「發(fā)送」按鈕,查看響應結果(狀態(tài)碼、響應體、響應頭)。
六、常見問題排查
1. 文檔頁面無法訪問
- 檢查
springdoc.swagger-ui.enabled和knife4j.enable配置是否為true(開發(fā)環(huán)境); - 確認依賴版本與 Spring Boot 版本兼容(如 Spring Boot 3.x 需使用 Knife4j 4.5.0+);
- 排查 Spring Security 或攔截器是否攔截了 Swagger 相關路徑,需手動放行。
2. 接口未顯示在文檔中
- 檢查控制器是否添加
@RestController注解,接口是否添加 HTTP 注解(@GetMapping/@PostMapping等); - 確認接口方法是否為
public權限(非public方法不會被掃描); - 檢查是否誤加
@Hidden注解,或是否配置了接口掃描范圍限制。
3. 注解不生效
- 確認導入的是
io.swagger.v3.oas.annotations包下的注解(而非 Swagger2 的io.swagger.annotations); - 檢查依賴是否完整(核心依賴
springdoc-openapi-starter-webmvc-ui不可缺失)。
七、總結
Swagger3(OpenAPI 3.0)通過 springdoc-openapi 與 Spring Boot 項目無縫集成,僅需簡單配置和注解,即可生成規(guī)范、可交互的 API 文檔,大幅降低前后端協(xié)作成本。
核心優(yōu)勢
- 實時同步:接口變更時,文檔自動更新,避免「文檔與代碼不一致」問題;
- 在線調試:支持直接在文檔頁面發(fā)送請求,無需依賴 Postman 等第三方工具;
- 靈活擴展:支持 JWT/OAuth2 認證、全局參數、分組排序等高級功能;
- 友好交互:Knife4j 增強 UI 提供更直觀的操作體驗,支持文檔導出(PDF/Markdown)。
最佳實踐
- 開發(fā)環(huán)境啟用 Swagger,生產環(huán)境強制禁用(避免接口暴露風險);
- 接口注解需完整(
@Tag+@Operation+@ApiResponses),參數和模型添加@Parameter/@Schema說明; - 結合 Spring Security 配置權限控制,保障文檔訪問安全;
- 定期更新依賴版本,確保兼容性和安全性。
通過本文的配置和示例,開發(fā)者可快速上手 Swagger3,并根據項目需求靈活擴展功能,讓 API 文檔成為前后端協(xié)作的「橋梁」而非「負擔」。
到此這篇關于Spring Boot Swagger3 使用指南的文章就介紹到這了,更多相關Spring Boot Swagger3 使用內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
SpringBoot3.2新特性之JdbcClient的使用
本文主要介紹了SpringBoot3.2新特性之JdbcClient的使用,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2025-08-08

