Spring?Boot?Swagger3常用注解詳解與實(shí)戰(zhàn)指南
前言
在 Spring Boot 項(xiàng)目開發(fā)中,API 文檔是前后端協(xié)作、項(xiàng)目維護(hù)的重要工具。Swagger3(OpenAPI 3.0)作為主流的 API 文檔生成工具,通過簡(jiǎn)單的注解就能快速生成規(guī)范化的 API 文檔,極大提升開發(fā)效率。本文將詳細(xì)介紹 Spring Boot 整合 Swagger3 的核心注解及實(shí)戰(zhàn)用法。
一、Swagger3 環(huán)境搭建(基礎(chǔ)準(zhǔn)備)
在使用注解前,需先完成 Spring Boot 與 Swagger3 的整合,步驟如下:
1. 引入依賴(Maven)
根據(jù) Spring Boot 版本選擇對(duì)應(yīng)依賴(Spring Boot 2.x/3.x 通用,3.x 需確保 JDK≥11):
<!-- Swagger3核心依賴 -->
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-boot-starter</artifactId>
<version>3.0.0</version>
</dependency>
<!-- 可選:Swagger UI美化依賴(推薦) -->
<dependency>
<groupId>com.github.xiaoymin</groupId>
<artifactId>knife4j-spring-boot-starter</artifactId>
<version>3.0.3</version>
</dependency>
2. 配置 Swagger3 核心類
import io.swagger.v3.oas.models.OpenAPI;
import io.swagger.v3.oas.models.info.Info;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class Swagger3Config {
// 定義API文檔全局信息
@Bean
public OpenAPI customOpenAPI() {
return new OpenAPI()
// 文檔標(biāo)題、描述、版本
.info(new Info()
.title("Spring Boot Swagger3 API文檔")
.description("基于Swagger3的接口文檔示例,包含用戶管理、訂單管理等模塊")
.version("v1.0.0")
// 可選:添加聯(lián)系人信息
.contact(new io.swagger.v3.oas.models.info.Contact()
.name("開發(fā)團(tuán)隊(duì)")
.email("dev@example.com")));
}
}
3. 啟動(dòng)類開啟 Swagger3
在 Spring Boot 啟動(dòng)類上添加@EnableOpenApi注解(Swagger3 專用,替代 Swagger2 的@EnableSwagger2):
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import springfox.documentation.oas.annotations.EnableOpenApi;
@SpringBootApplication
@EnableOpenApi // 開啟Swagger3文檔功能
public class Swagger3DemoApplication {
public static void main(String[] args) {
SpringApplication.run(Swagger3DemoApplication.class, args);
}
}
4. 訪問 Swagger UI
- 原生 Swagger UI:
http://localhost:8080/swagger-ui/index.html - Knife4j 美化 UI(推薦):
http://localhost:8080/doc.html
二、Swagger3 核心注解詳解
Swagger3 注解分為接口類注解、接口方法注解、參數(shù)注解、實(shí)體類注解四大類,以下是最常用的 10 個(gè)注解:
1. 接口類注解(Controller 層)
@Tag:描述 Controller 類
用于定義 Controller 的功能模塊,相當(dāng)于接口分組,屬性如下:
| 屬性名 | 作用 | 示例值 |
|---|---|---|
| name | 模塊名稱(必填) | “用戶管理模塊” |
| description | 模塊描述(可選) | “包含用戶新增、查詢、刪除接口” |
| order | 排序序號(hào)(可選) | 1(數(shù)字越小越靠前) |
使用示例:
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping("/api/user")
// 描述用戶管理模塊
@Tag(name = "用戶管理模塊", description = "提供用戶CRUD操作接口,支持分頁(yè)查詢和條件篩選")
public class UserController {
// 接口方法...
}
2. 接口方法注解(Controller 方法)
@Operation:描述接口方法
定義單個(gè)接口的功能、請(qǐng)求方式等核心信息,是方法級(jí)最核心的注解:
| 屬性名 | 作用 | 示例值 |
|---|---|---|
| summary | 接口簡(jiǎn)短描述(必填) | “新增用戶” |
| description | 接口詳細(xì)描述(可選) | “傳入用戶信息,創(chuàng)建新用戶,返回用戶 ID” |
| method | 請(qǐng)求方式(可選) | “POST”(默認(rèn)自動(dòng)識(shí)別) |
| hidden | 是否隱藏接口(可選) | false(true 不顯示在文檔) |
@ApiResponses & @ApiResponse:描述接口響應(yīng)
定義接口的多組響應(yīng)狀態(tài)(如成功、參數(shù)錯(cuò)誤、服務(wù)器異常):
@ApiResponses:用于包裹多個(gè)@ApiResponse@ApiResponse:?jiǎn)蝹€(gè)響應(yīng)狀態(tài)配置
使用示例:
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.responses.ApiResponse;
import io.swagger.v3.oas.annotations.responses.ApiResponses;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
@PostMapping("/add")
@Operation(summary = "新增用戶", description = "注意:用戶名需唯一,密碼需加密傳輸")
@ApiResponses({
@ApiResponse(responseCode = "200", description = "新增成功,返回用戶ID"),
@ApiResponse(responseCode = "400", description = "參數(shù)錯(cuò)誤(如用戶名為空、格式錯(cuò)誤)"),
@ApiResponse(responseCode = "500", description = "服務(wù)器異常,新增失敗")
})
public Result<Integer> addUser(@RequestBody UserDTO userDTO) {
// 業(yè)務(wù)邏輯...
return Result.success(userId);
}
3. 參數(shù)注解(方法參數(shù) / 請(qǐng)求體)
@Parameter:描述單個(gè)參數(shù)
用于方法的單個(gè)參數(shù)(如路徑參數(shù)、請(qǐng)求參數(shù)),支持指定參數(shù)說明、是否必傳等:
| 屬性名 | 作用 | 示例值 |
|---|---|---|
| name | 參數(shù)名(必填) | “userId” |
| description | 參數(shù)描述(可選) | “用戶 ID,用于查詢單個(gè)用戶” |
| required | 是否必傳(可選) | true(默認(rèn) false) |
| example | 示例值(可選) | “1001” |
使用示例(路徑參數(shù)):
import io.swagger.v3.oas.annotations.Parameter;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
@GetMapping("/{userId}")
@Operation(summary = "根據(jù)ID查詢用戶")
public Result<UserVO> getUserById(
@PathVariable
@Parameter(name = "userId", description = "用戶唯一ID", required = true, example = "1001")
Integer userId) {
// 業(yè)務(wù)邏輯...
return Result.success(userVO);
}
@RequestBody:描述請(qǐng)求體參數(shù)
用于標(biāo)記請(qǐng)求體參數(shù)(通常是 JSON 格式),并關(guān)聯(lián)實(shí)體類的@Schema注解:
使用示例:
@PostMapping("/update")
@Operation(summary = "更新用戶信息")
public Result<Boolean> updateUser(
@RequestBody
@Parameter(description = "用戶更新信息,userId必傳")
UserUpdateDTO userUpdateDTO) {
// 業(yè)務(wù)邏輯...
return Result.success(true);
}
4. 實(shí)體類注解(DTO/VO 層)
@Schema:描述實(shí)體類 / 字段
用于定義實(shí)體類(如 DTO、VO)及其字段的文檔說明,替代 Swagger2 的@ApiModel和@ApiModelProperty:
| 屬性名 | 作用 | 示例值 |
|---|---|---|
| title | 實(shí)體類描述(類級(jí)別) | “用戶新增請(qǐng)求 DTO” |
| description | 字段描述(字段級(jí)別) | “用戶名,長(zhǎng)度 1-20 字符” |
| required | 字段是否必傳(可選) | true(默認(rèn) false) |
| example | 字段示例值(可選) | “zhangsan” |
| hidden | 是否隱藏字段(可選) | false(true 不顯示在文檔) |
| format | 字段格式(可選) | “email”(如郵箱格式校驗(yàn)) |
使用示例(實(shí)體類):
import io.swagger.v3.oas.annotations.media.Schema;
import lombok.Data;
@Data
@Schema(title = "用戶新增請(qǐng)求DTO", description = "用于接收前端傳遞的用戶新增參數(shù)")
public class UserDTO {
@Schema(description = "用戶名(唯一)", required = true, example = "zhangsan", maxLength = 20)
private String username;
@Schema(description = "密碼(需加密)", required = true, example = "123456aA", minLength = 8)
private String password;
@Schema(description = "用戶年齡", example = "25", minimum = "18", maximum = "60")
private Integer age;
@Schema(description = "用戶郵箱", example = "zhangsan@example.com", format = "email")
private String email;
// 隱藏不需要在文檔中顯示的字段
@Schema(hidden = true)
private String createTime;
}
三、實(shí)戰(zhàn)案例:完整接口文檔示例
結(jié)合上述注解,實(shí)現(xiàn)一個(gè) “用戶管理” 模塊的完整 API 文檔,效果如下:
1. Controller 層(UserController)
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
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 org.springframework.web.bind.annotation.*;
@RestController
@RequestMapping("/api/user")
@Tag(name = "用戶管理模塊", description = "提供用戶新增、查詢、更新、刪除接口")
public class UserController {
@PostMapping("/add")
@Operation(summary = "新增用戶", description = "用戶名需唯一,密碼長(zhǎng)度≥8且包含大小寫字母")
@ApiResponses({
@ApiResponse(responseCode = "200", description = "新增成功"),
@ApiResponse(responseCode = "400", description = "參數(shù)錯(cuò)誤(如用戶名重復(fù))"),
@ApiResponse(responseCode = "500", description = "服務(wù)器異常")
})
public Result<Integer> addUser(@RequestBody @Parameter(description = "用戶新增參數(shù)") UserDTO userDTO) {
// 模擬業(yè)務(wù)邏輯:生成用戶ID
int userId = 1001;
return Result.success(userId);
}
@GetMapping("/{userId}")
@Operation(summary = "根據(jù)ID查詢用戶")
public Result<UserVO> getUserById(
@PathVariable
@Parameter(name = "userId", description = "用戶ID", required = true, example = "1001")
Integer userId) {
// 模擬查詢結(jié)果
UserVO userVO = new UserVO();
userVO.setUserId(userId);
userVO.setUsername("zhangsan");
userVO.setAge(25);
userVO.setEmail("zhangsan@example.com");
return Result.success(userVO);
}
}
2. 實(shí)體類(UserDTO & UserVO)
// UserDTO(請(qǐng)求體)
@Data
@Schema(title = "用戶新增DTO", description = "前端新增用戶時(shí)傳遞的參數(shù)")
public class UserDTO {
@Schema(description = "用戶名", required = true, example = "zhangsan", maxLength = 20)
private String username;
@Schema(description = "密碼", required = true, example = "123456aA", minLength = 8)
private String password;
@Schema(description = "年齡", example = "25", minimum = "18")
private Integer age;
}
// UserVO(響應(yīng)體)
@Data
@Schema(title = "用戶查詢VO", description = "后端返回給前端的用戶信息")
public class UserVO {
@Schema(description = "用戶ID", example = "1001")
private Integer userId;
@Schema(description = "用戶名", example = "zhangsan")
private String username;
@Schema(description = "年齡", example = "25")
private Integer age;
@Schema(description = "郵箱", example = "zhangsan@example.com")
private String email;
}
3. 訪問文檔效果
啟動(dòng)項(xiàng)目后,訪問http://localhost:8080/doc.html,可看到:
- 左側(cè)菜單顯示 “用戶管理模塊” 分組
- 展開分組可看到
/api/user/add和/api/user/{userId}兩個(gè)接口 - 點(diǎn)擊接口可查看參數(shù)說明、響應(yīng)狀態(tài)、實(shí)體類字段詳情
- 支持在線調(diào)試(填寫參數(shù)后點(diǎn)擊 “發(fā)送” 按鈕測(cè)試接口)
四、注意事項(xiàng)與最佳實(shí)踐
- 生產(chǎn)環(huán)境關(guān)閉 Swagger避免接口暴露,在
application-prod.yml中配置:
springfox: documentation: enabled: false
- 注解屬性簡(jiǎn)化非必填屬性(如
description)可根據(jù)需求省略,優(yōu)先保證name、summary、required等核心屬性。 - 參數(shù)示例規(guī)范化
example屬性需填寫真實(shí)場(chǎng)景的值(如郵箱格式、手機(jī)號(hào)格式),避免填寫 “test” 等無意義值。 - 實(shí)體類復(fù)用同一實(shí)體類在不同接口中(如新增和更新),可通過
@Schema(hidden = true)隱藏不需要的字段,無需重復(fù)創(chuàng)建實(shí)體類。
五、總結(jié)
- 類級(jí)別:
@Tag(分組描述) - 方法級(jí)別:
@Operation(接口描述)、@ApiResponses(響應(yīng)描述) - 參數(shù)級(jí)別:
@Parameter(單個(gè)參數(shù))、@RequestBody(請(qǐng)求體) - 實(shí)體類級(jí)別:
@Schema(字段描述)
掌握這些注解后,結(jié)合 Spring Boot 可快速生成規(guī)范化、可調(diào)試的 API 文檔,提升前后端協(xié)作效率。建議在項(xiàng)目初期就引入 Swagger3,并保持注解與業(yè)務(wù)邏輯同步更新。
到此這篇關(guān)于Spring Boot Swagger3常用注解詳解與實(shí)戰(zhàn)指南的文章就介紹到這了,更多相關(guān)Spring Boot Swagger3常用注解內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
SpringBoot重寫addResourceHandlers映射文件路徑方式
這篇文章主要介紹了SpringBoot重寫addResourceHandlers映射文件路徑方式,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2022-02-02
Mybatis-plus獲取雪花算法生成的ID并返回生成ID
本文主要介紹了Mybatis-plus獲取雪花算法生成的ID并返回生成ID,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2023-09-09
feign調(diào)用第三方接口,編碼定義GBK,響應(yīng)中文亂碼處理方式
這篇文章主要介紹了feign調(diào)用第三方接口,編碼定義GBK,響應(yīng)中文亂碼處理方式,具有很好的參考價(jià)值,希望對(duì)大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2024-01-01
從零開始在Centos7上部署SpringBoot項(xiàng)目
本文主要介紹了從零開始在Centos7上部署SpringBoot項(xiàng)目,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2022-04-04
SpringBoot中的server.context-path的實(shí)現(xiàn)
本文主要介紹了SpringBoot中的server.context-path的實(shí)現(xiàn),文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2024-08-08
Spring Boot配置線程池拒絕策略的場(chǎng)景分析(妥善處理好溢出的任務(wù))
本文通過實(shí)例代碼給大家介紹下如何為線程池配置拒絕策略、如何自定義拒絕策略。對(duì)Spring Boot配置線程池拒絕策略的相關(guān)知識(shí)感興趣的朋友一起看看吧2021-09-09

