【SpringDoc 基本使用指南】
(基于 Spring Boot 3.x / 4.x + SpringDoc 2.x / 3.x 系列,2026年3月最新推荐做法)
SpringDoc 是目前 Spring 生态中最活跃、最推荐的 OpenAPI 3.x 文档生成工具(取代了已停止维护的 SpringFox),它几乎零配置就能工作,支持:
- 自动扫描
@RestController、@Operation、@Parameter、@Schema等注解 - 生成 JSON/YAML 规范(/v3/api-docs)
- 内置 Swagger UI(/swagger-ui.html) + Scalar / Redoc 等现代 UI
- 支持 Spring Boot 3.x(Jakarta EE)、WebMVC / WebFlux、Security、Validation 等
1. 快速起步(最常用依赖)
在 pom.xml 中添加 一个依赖 即可(带 UI 的 starter):
<dependency>
<groupId>org.springdoc</groupId>
<artifactId>springdoc-openapi-starter-webmvc-ui</artifactId>
<!-- 推荐使用最新稳定版(2026年3月主流) -->
<version>2.8.16</version> <!-- 或 3.0.2 如果你用 Spring Boot 4.x + OpenAPI 3.1 -->
</dependency>
- 如果你只需要 JSON/YAML 不需要 UI:用
springdoc-openapi-starter-webmvc-api - WebFlux 项目:换成
springdoc-openapi-starter-webflux-ui
零配置启动后,直接访问:
- Swagger UI(交互式文档):
http://localhost:8080/swagger-ui.html
(或新版路径:/swagger-ui/index.html) - OpenAPI JSON:
http://localhost:8080/v3/api-docs - OpenAPI YAML:
http://localhost:8080/v3/api-docs.yaml
2. 常用 application.yml 配置(推荐放一份)
springdoc:
# API 文档基础路径(默认 /v3/api-docs)
api-docs:
path: /v3/api-docs
enabled: true
# Swagger UI 路径(默认 /swagger-ui.html)
swagger-ui:
path: /swagger-ui.html
# 是否启用 Try it out 功能(生产建议关闭)
try-it-out-enabled: true
# 默认展开所有 tag
doc-expansion: list
# 显示请求耗时
display-request-duration: true
# 操作按 HTTP 方法排序
operationsSorter: method
# 标签排序(alpha / method)
tagsSorter: alpha
# 是否显示 actuator 端点(默认不显示)
show-actuator: false
# 扫描的包路径(可选,多数情况自动扫描即可)
# packages-to-scan: com.yourcompany.controller,com.yourcompany.dto
# 扫描的路径(排除健康检查等)
paths-to-match: /api/**
# 自定义文档信息(优先级低于 @OpenAPIDefinition)
info:
title: 用户中心 API
description: 重阳的 Spring Boot 项目接口文档
version: 1.0.0-RELEASE
contact:
name: 重阳
email: your@email.com
3. 推荐的 Controller 写法(带常用注解)
import io.swagger.v3.oas.annotations.*;
import io.swagger.v3.oas.annotations.media.*;
import io.swagger.v3.oas.annotations.responses.*;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
@Tag(name = "用户管理", description = "用户注册、登录、个人信息相关接口")
@RestController
@RequestMapping("/api/v1/users")
public class UserController {
@Operation(
summary = "用户注册",
description = "创建新用户账号"
)
@ApiResponses({
@ApiResponse(responseCode = "201", description = "注册成功",
content = @Content(schema = @Schema(implementation = UserVO.class))),
@ApiResponse(responseCode = "400", description = "参数校验失败"),
@ApiResponse(responseCode = "409", description = "用户名已存在")
})
@PostMapping("/register")
public ResponseEntity<UserVO> register(
@RequestBody @Validated @io.swagger.v3.oas.annotations.parameters.RequestBody(
description = "注册信息", required = true,
content = @Content(schema = @Schema(implementation = UserRegisterDTO.class))
) UserRegisterDTO dto) {
// 业务逻辑...
return ResponseEntity.status(201).body(new UserVO());
}
@Operation(summary = "获取当前用户信息", security = @SecurityRequirement(name = "bearerAuth"))
@GetMapping("/me")
public ResponseEntity<UserVO> getCurrentUser() {
// ...
}
}
常用注解速查:
| 注解位置 | 注解 | 作用 |
|---|---|---|
| 类 | @Tag | 分组(显示在左侧菜单) |
| 方法 | @Operation(summary, description) | 接口标题 + 详细说明 |
| 方法 | @ApiResponses / @ApiResponse | 各种响应码的说明 |
| 参数 | @Parameter | 查询参数/路径参数说明 |
| 请求体 | @RequestBody + @io...RequestBody | 示例、必填、schema 指定 |
| DTO 类字段 | @Schema(description, example) | 字段说明 + 示例值 |
4. 全局自定义 OpenAPI(推荐方式)
@Configuration
public class OpenApiConfig {
@Bean
public OpenAPI customOpenAPI() {
return new OpenAPI()
.info(new Info()
.title("重阳的 API 文档")
.version("1.0")
.description("基于 Spring Boot + SpringDoc 的接口规范")
.contact(new Contact().name("重阳").email("xxx@xxx.com"))
.license(new License().name("Apache 2.0").url("https://www.apache.org/licenses/"))
)
.addServersItem(new Server().url("/").description("本地开发"))
.addServersItem(new Server().url("https://api.yourdomain.com").description("生产环境"))
// 如果有 JWT 等全局鉴权
.components(new Components()
.addSecuritySchemes("bearerAuth",
new SecurityScheme()
.type(SecurityScheme.Type.HTTP)
.scheme("bearer")
.bearerFormat("JWT")
)
)
.addSecurityItem(new SecurityRequirement().addList("bearerAuth"));
}
}
5. 常见问题 & 避坑(2026年高频)
| 问题 | 解决办法 |
|---|---|
| 访问 /swagger-ui.html 404 | 确认依赖带 -ui 后缀;检查路径是否被 Security 拦截 |
| Security 拦截 Swagger | 在 Security 配置中 .requestMatchers("/v3/api-docs/**", "/swagger-ui/**", "/swagger-ui.html").permitAll() |
| 文档里没有示例值 | 在 DTO 字段加 @Schema(example = "13800138000") |
| 想用中文标题/描述乱码 | 确保项目编码 UTF-8;Spring Boot 默认已支持 |
| 生产环境关闭 Swagger | spring.profiles.active=prod 时设置 springdoc.swagger-ui.enabled=false |
| 分组文档(多个模块) | 用 springdoc.group-configs 或 @Tag + GroupedOpenApi Bean |
6. 推荐下一阶段学习路径
- 集成 Spring Security + JWT(全局 bearerAuth)
- 用
@Schema+@ExampleObject丰富请求/响应示例 - 配置多环境分组(dev/test/prod 不同文档)
- 导出静态 OpenAPI YAML(用于生成前端 SDK)
- 对比 Scalar UI / Redoc(更现代的替代 Swagger UI)
你的项目现在是用 Spring Boot 3.x 还是 4.x?
有没有已经加了 Spring Security?
想重点解决哪个问题(比如加鉴权、自定义示例、分组文档)?
告诉我具体场景,我可以直接给你针对性的配置片段或完整示例类。