Spring Boot 4 接口文档(Springdoc + Scalar)使用教程
目录
一、引言
1.1 为什么需要接口文档
一份准确的接口文档要回答四个问题:
- 有哪些接口——路径、方法、用途;
- 怎么调用——参数位置、类型、是否必填、示例值;
- 返回什么——响应体结构、状态码、业务错误怎么表达;
- 怎么联调——能不能直接发请求看真实响应。
手写 Markdown 维护这四件事,注定会与代码脱节——接口改了、文档没改,是所有团队都会踩的坑。而 springdoc 的思路是把文档当作代码结构的另一种投影:不写文档,而是从代码里反射出来。
本文档介绍在 Spring Boot 4 下用 springdoc-openapi 3.x + Scalar 搭建这套体系的全过程,面向的是任何使用 Spring Boot 4 的 RESTful 服务,与具体业务无关。
1.2 Spring Boot 4 带来的版本约束
网上大多数 Spring Boot 接口文档教程给的是 Spring Boot 3 时代的答案,直接抄会踩坑。Spring Boot 4(Spring Framework 7 / Jakarta EE 11)带来两处关键变化:
| 维度 | Spring Boot 3 | Spring Boot 4 | 后果 |
|---|---|---|---|
| springdoc-openapi | 2.x(如 2.8.17) | 3.x(当前 3.2.0) | 用 2.x 会因内部 API 变更直接启动失败 |
| Knife4j | 4.5.0 / 4.6.0.1 可用 | 不可用 | 4.6.0.1 内部锁死 Spring Boot 3.5.7 + springdoc 2.8.14 |
结论是:Spring Boot 4 时代只剩 springdoc 一条路,区别只在于用哪个 UI 前端渲染同一份 spec。
版本与工具的对应关系
1.3 文档工具的发展脉络
值得注意的是最后一条分支:springdoc 3.x 把 Scalar 直接收编为官方 starter(springdoc-openapi-starter-webmvc-scalar),其父 POM 里能看到 com.scalar.maven:scalar-core 的依赖管理。这意味着 Scalar 不再是第三方野鸡包,而是官方一等公民。
二、核心概念
2.1 OpenAPI 3.1 规范基础
OpenAPI 是描述 HTTP 接口的机器可读规范。一份 spec 的顶层结构如下:
| 字段 | 含义 | 典型取值 |
|---|---|---|
openapi |
规范版本 | 3.1.0 |
info |
标题、版本号、描述、联系人 | title / version / description |
servers |
服务地址列表 | http://localhost:8080 |
tags |
接口分组 | 用户管理、订单管理、系统运维 |
paths |
路径 → 操作 | 每个操作含 parameters / requestBody / responses |
components.schemas |
可复用的数据结构 | DTO 对应的数据模型 |
components.securitySchemes |
鉴权方案定义 | bearerAuth / apiKey |
一个操作(operation)内部的关键字段:
parameters:路径参数与查询参数,含name/in/required/schema;requestBody:请求体,含content(媒体类型 → schema);responses:响应码 → 响应描述与内容类型。
2.2 springdoc 的工作原理
springdoc 不是一个静态扫描工具,它在运行时通过反射生成 spec:
接口文档自动生成链路
图片说明:本示意图为本地脚本生成的原创 SVG,绘制逻辑参考 springdoc 官方模块划分。
理解了这条链路,就能明白两个常见困惑的根因:
- "为什么我加了注解但文档没变?" —— 注解只影响分组与描述,schema 由方法签名与返回类型决定;
- "为什么请求体里没有任何字段?" ——
Map<String, Object>在 OpenAPI 里只能表达成"任意键值对",反射拿不到字段清单。
2.3 Scalar UI 的界面构成
Scalar 是 springdoc 3.x 官方内置的渲染前端。它的界面可以拆成五个区域:
Scalar UI 界面功能区示意
各区域对应的能力:
| 区域 | 功能 | 实用场景 |
|---|---|---|
| 顶部工具栏 | Search(⌘K 快速跳转)、Ask AI(问接口怎么用)、Generate SDK | 接口一多,靠目录翻找效率低下,⌘K 更快 |
| 左侧导航 | 按 tag 分组的接口树 | 分组折叠后一眼看全所有接口 |
| 中间正文 | 标题、描述、Server、参数表、请求体、响应码 | 排查「这个接口到底收什么」 |
| 右侧试调 | Try it 面板,直接发请求看真实响应 | 联调前自测,不用切 Postman |
| 底部工具 | Generate SDKs & MCP、Copy as Markdown | 把接口变成 AI Agent 可调用的工具 |
2.4 一份典型 RESTful 服务的接口形态
本文档后续所有示例,都以一份经典的用户管理服务为准:
| 分组 | 方法 | 路径 | 参数 | 说明 |
|---|---|---|---|---|
| 用户管理 | GET | /api/users |
page、size、keyword |
分页查询,缺省返回第一页 20 条 |
| 用户管理 | POST | /api/users |
JSON body | 创建用户,用户名唯一 |
| 用户管理 | GET | /api/users/{id} |
路径参数 id |
查询单个用户,不存在返回 404 |
| 用户管理 | PUT | /api/users/{id} |
路径参数 id + JSON body |
全量更新 |
| 用户管理 | DELETE | /api/users/{id} |
路径参数 id |
删除,成功返回 204 |
| 订单管理 | GET | /api/orders |
userId |
按用户查询订单列表 |
对应的 Controller 骨架:
@RestController
@RequestMapping("/api/users")
public class UserController {
@GetMapping
public Page<UserDTO> list(@RequestParam(defaultValue = "0") int page,
@RequestParam(defaultValue = "20") int size,
@RequestParam(required = false) String keyword) { ... }
@PostMapping
@ResponseStatus(HttpStatus.CREATED)
public UserDTO create(@RequestBody @Valid UserCreateDTO body) { ... }
@GetMapping("/{id}")
public UserDTO get(@PathVariable Long id) { ... }
@PutMapping("/{id}")
public UserDTO update(@PathVariable Long id, @RequestBody @Valid UserUpdateDTO body) { ... }
@DeleteMapping("/{id}")
@ResponseStatus(HttpStatus.NO_CONTENT)
public void delete(@PathVariable Long id) { ... }
}
这份骨架就是后面所有章节的实验对象。
三、详细说明
3.1 依赖安装与版本约束
pom.xml 中的写法:
<properties>
<!--
OpenAPI 文档(springdoc)版本:
2.x 只支持 Spring Boot 3,3.x 才支持 Spring Boot 4,别降级。
换 UI 只改 artifactId:
springdoc-openapi-starter-webmvc-scalar → /scalar (Scalar,推荐)
springdoc-openapi-starter-webmvc-ui → /swagger-ui.html (经典 Swagger UI)
-->
<springdoc-openapi.version>3.2.0</springdoc-openapi.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springdoc</groupId>
<artifactId>springdoc-openapi-starter-webmvc-scalar</artifactId>
<version>${springdoc-openapi.version}</version>
</dependency>
</dependencies>
几个选型要点:
| 决策点 | 说明 |
|---|---|
| webmvc 还是 webflux | 取决于你的技术栈是 servlet 还是 reactive。本文以 spring-boot-starter-webmvc 为例,WebFlux 项目换成 springdoc-openapi-starter-webflux-scalar |
| Scalar 还是 Swagger UI | 两者共用同一份 spec,只换渲染层。Scalar 的现代交互、SDK 生成、Ask AI 更适合新项目 |
| 版本号写死还是走 BOM | springdoc 官方提供 BOM,可用 springdoc-openapi-bom 统一管理多模块版本 |
| Knife4j | Spring Boot 4 下不可用,理由见 1.2 节 |
Knife4j 不可用的原因很具体:
io.github.lisi9988:knife4j-openapi3-jakarta-spring-boot-starter:4.6.0.1的父 POM 里写死了<knife4j-spring-boot3.version>3.5.7</...>与<knife4j-springdoc-openapi-jakarta.version>2.8.14</...>,它会把 springdoc 2.x 传递进来,与 Boot 4 冲突。
3.2 OpenApiConfig 元信息配置
配置类负责 spec 的顶层元信息:
@Configuration
public class OpenApiConfig {
@Bean
public OpenAPI openApi() {
return new OpenAPI()
.info(new Info()
.title("用户服务 API")
.version("v1")
.description("""
用户增删改查的 HTTP 接口。
**约定**:
- 所有列表接口均为分页返回,`page` 从 0 开始
- 业务错误统一返回 `{ "code": 40001, "message": "..." }`
- 写操作需要 `Authorization: Bearer <token>` 请求头
""")
.contact(new Contact().name("平台组").email("api@example.com"))
.license(new License().name("Apache 2.0")))
.servers(List.of(
new Server().url("http://localhost:8080").description("本地开发"),
new Server().url("https://api.example.com").description("生产环境")))
.externalDocs(new ExternalDocumentation()
.description("更多背景说明")
.url("https://wiki.example.com/api"));
}
}
四个要点:
- description 用 Markdown 写:Scalar 会渲染 Markdown,可以在描述里写表格、代码块、列表。跨接口通用的约定(分页规则、错误码格式、鉴权方式)写在这里,比散落在几十个方法注释里更好维护。
- servers 要写全:不写的话 Scalar 的 Try it 会默认打到当前域名,生产环境部署到别的域名时就会请求错地址。
- 多 environment 就多写几个 Server:Scalar 会把它们渲染成下拉框,联调时切换环境很方便。
- description 是 JSON 里的换行字符串:Java 的文本块
"""编译后是\n,正好符合 OpenAPI 描述字段的语义。
3.3 注解体系
Swagger 注解来自 io.swagger.v3.oas.annotations 包,springdoc 会自动扫描。
类级分组:
@RestController
@RequestMapping("/api/users")
@Tag(name = "用户管理", description = "用户的增删改查与分页查询")
public class UserController {
方法级的常用组合:
@Operation(
summary = "创建用户",
description = "用户名唯一,重复时返回 409 Conflict",
operationId = "createUser")
@ApiResponses({
@ApiResponse(responseCode = "201", description = "创建成功"),
@ApiResponse(responseCode = "409", description = "用户名已存在",
content = @Content(schema = @Schema(implementation = ErrorResponse.class)))
})
@PostMapping
@ResponseStatus(HttpStatus.CREATED)
public UserDTO create(@RequestBody @Valid UserCreateDTO body) { ... }
参数级:
@Parameter(description = "用户 ID", example = "1001")
@GetMapping("/{id}")
public UserDTO get(@PathVariable Long id) { ... }
DTO 字段级:
public record UserCreateDTO(
@Schema(description = "登录名", example = "zhangsan", requiredMode = RequiredMode.REQUIRED)
@NotBlank(message = "用户名不能为空")
@Size(max = 32, message = "用户名最长 32 个字符")
String username,
@Schema(description = "昵称", example = "张三")
@Size(max = 64)
String nickname,
@Schema(description = "邮箱", example = "zhangsan@example.com")
@Email(message = "邮箱格式不正确")
String email) {
}
注解速查:
| 注解 | 作用位置 | 典型用途 |
|---|---|---|
@Tag |
类 | 分组名与分组说明 |
@Operation |
方法 | 接口摘要、详细描述、operationId |
@Parameter |
参数 | 参数含义与示例值 |
@ApiResponse |
方法 | 声明非 2xx 响应及其 schema |
@Schema |
DTO 字段 | 字段说明、示例、是否必填、取值范围 |
@Hidden |
类 / 方法 | 把内部接口从文档里剔除 |
@SecurityScheme |
配置类 | 声明 Bearer / API Key 鉴权方式 |
@Hidden 值得单独提一句:内部运维接口生产环境本来就该加鉴权,用 @Hidden 可以让它在对外文档里直接消失,比"文档里挂着但别人调不了"干净。
3.4 application.yml 全部可用配置项
# ── OpenAPI 接口文档(Springdoc + Scalar UI)────────────────────────────
# UI http://localhost:8080/scalar 人看的
# spec http://localhost:8080/v3/api-docs OpenAPI 3.1 JSON
springdoc:
api-docs:
enabled: true
path: /v3/api-docs
# 只扫描指定包,避免把第三方 jar 里的 Controller 也扫进来
packages-to-scan: com.example.api
packages-to-exclude: com.example.internal
paths-to-match: /api/**
# 别把 actuator 的端点混进接口文档
show-actuator: false
# 开启后文档变化时立刻重新生成,不用重启
cache:
disabled: true
scalar:
enabled: true
page-title: 用户服务 API
dark-mode: true
springdoc 常用配置项:
| 配置项 | 默认值 | 说明 |
|---|---|---|
springdoc.api-docs.enabled |
true |
关闭后 /v3/api-docs 返回 404 |
springdoc.api-docs.path |
/v3/api-docs |
spec 的挂载路径 |
springdoc.packages-to-scan |
全扫 | 只扫描指定包 |
springdoc.packages-to-exclude |
无 | 排除指定包 |
springdoc.paths-to-match |
全匹配 | 只包含匹配这些路径的接口 |
springdoc.paths-to-exclude |
无 | 排除匹配这些路径的接口 |
springdoc.show-actuator |
false |
是否收录 actuator 端点 |
springdoc.cache.disabled |
false |
关掉 spec 缓存 |
springdoc.default-flat-param-object |
true |
把扁平参数合并成一个对象 |
springdoc.default-produces-media-type |
*/* |
默认响应媒体类型 |
springdoc.writer-with-order-by-keys |
false |
spec 的 key 按字母序输出 |
Scalar 侧还有更多可调项(属性前缀 scalar,来自 com.scalar.maven.core.ScalarProperties):
| 属性 | 默认值 | 说明 |
|---|---|---|
scalar.enabled |
true |
关闭后 /scalar 返回 404 |
scalar.path |
/scalar |
UI 挂载路径 |
scalar.page-title |
Scalar API Reference |
浏览器标签页标题 |
scalar.dark-mode |
false |
暗色模式 |
scalar.show-sidebar |
true |
是否显示左侧导航 |
scalar.hide-models |
false |
隐藏数据模型区 |
scalar.hide-test-request-button |
false |
隐藏 Try it 按钮 |
scalar.hide-search |
false |
隐藏搜索框 |
scalar.favicon |
favicon.svg |
站点图标 |
Scalar 的这些属性由
com.scalar.maven.core.ScalarProperties提供,与 springdoc 的springdoc.*是两套独立命名空间,改错了不会报错但也不会生效——排查时先确认前缀。
3.5 Scalar UI 五大功能区实操
① 搜索(⌘K)
接口超过 20 个之后目录翻找效率骤降。点击左上角 Search 或按 ⌘K / Ctrl+K,输入关键词(如 users、orders)直达。
② Ask AI
选中某个接口后点 Ask AI,可以直接用自然语言问「创建用户返回 409 的条件是什么」「删除接口的副作用有哪些」。它读的是当前页面的 spec 内容,答案质量取决于 spec 的描述写得详不详细——这反过来证明了 description 质量的重要性。
③ Generate SDK
点击后选择目标语言,Scalar 会基于 spec 生成可运行的调用代码:
| 语言 | 产物形态 |
|---|---|
| Shell | cURL 命令 |
| JavaScript / TypeScript | axios / fetch 调用 |
| Python | requests 调用 |
| PHP / Ruby / Go / Java / C# | 对应语言的调用片段 |
也可以点左下角 Generate SDKs & MCP,进入完整 SDK 生成页面(支持更多语言与包管理器)。
④ Try it
在接口正文右侧点 Try it,选择 Server、填参数、发请求,响应直接显示在页面里。参数如果带 @Schema(example=...),输入框会自动预填示例值,不用自己想测试数据。
⑤ Copy as Markdown
每个接口右下角有这个按钮,一键把该接口的完整定义复制成 Markdown。适合贴到需求文档、PR 描述或聊天窗口里。
3.6 SSE 流式接口在文档中的表现
Spring MVC 的 SseEmitter 返回类型会被 springdoc 识别为 text/event-stream 响应:
"/api/events": {
"get": {
"tags": ["系统运维"],
"parameters": [
{ "name": "topic", "in": "query", "schema": { "type": "string" } }
],
"responses": {
"200": { "content": { "text/event-stream": { "schema": { "type": "string" } } } }
}
}
}
需要注意的是:OpenAPI 规范本身不描述 SSE 的事件语义,它只声明"这是一个 event-stream 响应"。事件名(message / progress / error)对外部工具是不可见的。
因此流式接口的事件约定应该写进两处:
OpenApiConfig的info.description(全局说明,人在 Scalar 上能看到);- Controller 的类注释与
@Operation(description=...)(贴近代码,开发者能看到)。
如果希望事件语义也进机器可读的 spec,可以用 @ApiResponse 配合 content 显式声明每种事件的数据结构。
3.7 文档的下游消费链路
一条 spec 的多路复用是接口文档最大的价值:写一次,五处受益。
3.8 构建期导出静态接口契约
除了运行时的 UI,还常需要一份能进 git 的静态契约(前端仓库、离线文档、评审附件都需要)。推荐用「导出 spec + 静态站点」的方式,稳妥且不引入版本风险:
# 1. 启动应用(后台)
mvn spring-boot:run &
# 2. 等待就绪后导出 spec
curl -s http://localhost:8080/v3/api-docs -o docs/openapi.json
# 3. 用 Redoc / Scalar CLI 渲染成静态站点
npx @redocly/cli build-docs docs/openapi.json -o docs/index.html
也可以在 pom.xml 里挂 maven 插件自动导出:
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>exec-maven-plugin</artifactId>
<version>3.1.0</version>
<executions>
<execution>
<id>export-openapi</id>
<phase>package</phase>
<goals><goal>exec</goal></goals>
<configuration>
<executable>bash</executable>
<arguments>
<argument>-c</argument>
<argument>curl -s http://localhost:8080/v3/api-docs -o docs/openapi.json</argument>
</arguments>
</configuration>
</execution>
</executions>
</plugin>
关于
org.springdoc:springdoc-openapi-maven-plugin:官方确实有这个插件(用于生成 Asciidoctor/Markdown 静态文档),但其最新发布版本停留在 1.6,是 springdoc 1.x 时代的产物,与 Boot 4 / springdoc 3.x 的组合未经验证。生产项目建议用上面的导出 + 静态站点方案。
四、示例
4.1 最小上手示例
目标:从零到打开文档页面。
步骤一:确认依赖已就位
mvn dependency:tree | grep springdoc
期望输出:
[INFO] +- org.springdoc:springdoc-openapi-starter-webmvc-scalar:jar:3.2.0:compile
[INFO] | +- org.springdoc:springdoc-openapi-starter-webmvc-api:jar:3.2.0:compile
[INFO] | +- com.scalar.maven:scalar-webmvc:jar:0.6.83:compile
[INFO] | \- com.scalar.maven:scalar-core:jar:0.6.83:compile
步骤二:启动应用
mvn spring-boot:run
启动日志末尾会出现这两行 WARN,这是正常提示而非错误:
WARN o.s.core.events.SpringDocAppInitializer : SpringDoc /v3/api-docs endpoint is enabled by default.
To disable it in production, set the property 'springdoc.api-docs.enabled=false'
WARN o.s.core.events.SpringDocAppInitializer : SpringDoc /scalar endpoint is enabled by default.
To disable it in production, set the property 'scalar.enabled=false'
步骤三:打开文档
http://localhost:8080/scalar
步骤四:确认 spec 可访问
http://localhost:8080/v3/api-docs
4.2 用 curl 校验生成的 spec
# 看顶层元信息
curl -s http://localhost:8080/v3/api-docs | python -c "
import json,sys
d=json.load(sys.stdin)
print('spec 版本 :', d['openapi'])
print('标题 :', d['info']['title'])
print('服务器 :', [s['url'] for s in d.get('servers',[])])
print('分组 :', [t['name'] for t in d.get('tags',[])])
print('操作总数 :', sum(len(v) for v in d['paths'].values()))
"
实际输出:
spec 版本 : 3.1.0
标题 : 用户服务 API
服务器 : ['http://localhost:8080', 'https://api.example.com']
分组 : ['用户管理', '订单管理', '系统运维']
操作总数 : 6
列出全部操作:
curl -s http://localhost:8080/v3/api-docs | python -c "
import json,sys
d=json.load(sys.stdin)
for p,ops in d['paths'].items():
for m,o in ops.items():
ps=', '.join(x['name'] for x in o.get('parameters',[])) or '-'
print('%-6s %-24s %s'%(m.upper(),p,ps))
"
GET /api/users page, size, keyword
POST /api/users -
GET /api/users/{id} id
PUT /api/users/{id} id
DELETE /api/users/{id} id
GET /api/orders userId
4.3 在 Scalar 中调试一个 CRUD 接口
在 UI 里操作:
-
打开
http://localhost:8080/scalar -
左侧展开「用户管理」
-
点
POST /api/users -
右侧 Try it → 在 Request Body 里填:
{ "username": "zhangsan", "nickname": "张三", "email": "zhangsan@example.com" } -
Send
预期响应:
{
"id": 1001,
"username": "zhangsan",
"nickname": "张三",
"email": "zhangsan@example.com",
"createdAt": "2026-01-08T10:30:00"
}
用 curl 等价复现:
curl -X POST http://localhost:8080/api/users \
-H "Content-Type: application/json" \
-d '{"username":"zhangsan","nickname":"张三","email":"zhangsan@example.com"}'
如果用户名重复,会返回 409——这个状态码在 @ApiResponses 里声明过,Scalar 的响应区会显示对应的说明。
4.4 调试 SSE 流式接口
在 UI 里操作:
- 左侧展开「系统运维」
- 点
GET /api/events - 右侧 Try it → 填
topic=order-status→ Send
用 curl 等价复现(更直观,能看到原始字节流):
curl -N -H "Accept: text/event-stream" \
"http://localhost:8080/api/events?topic=order-status"
预期输出:
event:message
data:{"orderId":"SO-2026-0001","status":"PAID"}
event:message
data:{"orderId":"SO-2026-0002","status":"SHIPPED"}
event:error
data:{"code":50001,"message":"上游推送通道断开"}
注意:curl 默认不带
Accept: text/event-stream,但若接口没有严格的produces约束,缺省也能通。加上的好处是能明确验证 content-type 协商结果为text/event-stream而不是406。
4.5 生成 TypeScript SDK 示例
# 1. 导出 spec
curl -s http://localhost:8080/v3/api-docs -o openapi.json
# 2. 生成 TypeScript fetch 客户端
npx @openapitools/openapi-generator-cli generate \
-i openapi.json \
-g typescript-fetch \
-o ./generated-client
生成物结构:
generated-client/
├── apis/
│ ├── UserControllerApi.ts
│ ├── OrderControllerApi.ts
│ └── ...
├── models/
│ ├── UserDTO.ts
│ ├── UserCreateDTO.ts
│ └── ...
└── runtime.ts
调用示例:
import { UserControllerApi, Configuration } from './generated-client';
const api = new UserControllerApi(new Configuration({
basePath: 'http://localhost:8080'
}));
// 分页查询
const page = await api.list({ page: 0, size: 20 });
console.log(page.content?.map(u => u.username));
// 创建
const created = await api.create({
userCreateDTO: { username: 'lisi', nickname: '李四', email: 'lisi@example.com' }
});
生成前建议先把入参/出参都改成 DTO(见 5.1 节),否则生成的 models 里只有一堆
object,类型安全无从谈起。
4.6 导入 Apifox 示例
- 打开 Apifox → 新建项目 → 导入 → OpenAPI/Swagger
- 填写 spec 地址:
http://localhost:8080/v3/api-docs - 导入后自动生成接口树、请求参数、响应示例
- 需要 Mock 时,可在 Apifox 里基于 schema 配置 Mock 规则,前端在后端未就绪时也能联调
Apifox 的价值在于把「设计 → 调试 → Mock → 自动化测试 → 团队协作」串成一条流水线;如果你只是需要「把接口信息展示出来」,Scalar 足够且更轻。
4.7 从 spec 生成 MCP Server 示例
这是 Scalar 相比 Swagger UI 最新的差异点:把你的 HTTP 接口变成 MCP(Model Context Protocol) 工具,让 Claude Code、Cursor 这类 AI Agent 直接调用你的接口。
操作路径:
- 打开
http://localhost:8080/scalar - 点击左下角 Generate SDKs & MCP
- 选择目标 MCP 运行时(Node.js / Python 等),复制生成的配置片段
Scalar 侧的 MCP 有两类部署形态:
| 形态 | 地址 | 适用场景 |
|---|---|---|
| Docs MCP | https://<你的文档域名>/mcp |
文档自托管时,接口跟随文档站点的可见性 |
| Installation MCP(托管) | https://mcp.scalar.com/mcp/<安装 ID> |
Scalar 云端安装,默认私有,无凭据返回 401 |
接入 Claude Code 的方式:
claude mcp add my-api https://mcp.scalar.com/mcp/YOUR_INSTALL_ID
工具模式决定 Agent 的能力边界:
| 模式 | 能力 |
|---|---|
| Search | 只暴露接口目录供查询,不真正发请求 |
| Execute | 真正发起带鉴权的 HTTP 请求(AI Agent 可直接调你的接口) |
鉴权模式:
| 模式 | 行为 |
|---|---|
| Global | 一份凭据存在安装侧(OAuth / API Key / Bearer) |
| Passthrough | 由调用方每次请求自带凭据,服务端不存储 |
如果不想依赖 Scalar 云端,本地可以用开源方案把 spec 转成 MCP Server:
npx agentic-openapi-mcp http://localhost:8080/v3/api-docs
{
"mcpServers": {
"my-api": {
"command": "npx",
"args": ["-y", "agentic-openapi-mcp", "http://localhost:8080/v3/api-docs"]
}
}
}
接入后,AI Agent 就能列出并调用你的接口:
> 创建一个用户,username 叫 wangwu
提醒:Execute 模式会让外部 Agent 真实调用你的接口。删除类接口务必在暴露前用
@Hidden或独立的 MCP Server 实例剔除。
4.8 用 GroupedOpenApi 分组示例
当接口数量继续增长,可以在配置类里加分组,生成多份 spec:
@Bean
public GroupedOpenApi userApi() {
return GroupedOpenApi.builder()
.group("user")
.pathsToMatch("/api/users/**")
.build();
}
@Bean
public GroupedOpenApi orderApi() {
return GroupedOpenApi.builder()
.group("order")
.pathsToMatch("/api/orders/**")
.build();
}
分组后的访问方式:
| 分组名 | spec 地址 |
|---|---|
| user | http://localhost:8080/v3/api-docs/user |
| order | http://localhost:8080/v3/api-docs/order |
| 全部(默认) | http://localhost:8080/v3/api-docs |
分组类路径在 springdoc 3.2.0 中为 org.springdoc.core.models.GroupedOpenApi(注意是 models 子包)。
五、最佳实践
5.1 让文档自动精确到字段
假设 Controller 直接接收 Map<String, Object>:
@PostMapping
public UserDTO create(@RequestBody Map<String, Object> body) { ... }
生成出来的请求体是这样的:
{ "type": "object", "additionalProperties": {} }
这在 OpenAPI 里是合法但无信息量的写法——任何键值都合法,等于没描述。
改造方式是把入参抽成 record:
/**
* 创建用户的请求体。
*
* <p>抽成 record 而不是 Map 的原因:Map 在 OpenAPI 里只能表达成空 object,
* 文档里看不到任何字段,前端和联调都得靠猜。record 能自动生成 schema,
* 配合 {@code @Schema} 还能给出字段说明与示例值。
*/
public record UserCreateDTO(
@Schema(description = "登录名", example = "zhangsan",
requiredMode = RequiredMode.REQUIRED)
@NotBlank(message = "用户名不能为空")
@Size(max = 32, message = "用户名最长 32 个字符")
String username,
@Schema(description = "昵称", example = "张三")
@Size(max = 64, message = "昵称最长 64 个字符")
String nickname,
@Schema(description = "邮箱", example = "zhangsan@example.com")
@Email(message = "邮箱格式不正确")
String email) {
}
Controller 改用:
@PostMapping
@ResponseStatus(HttpStatus.CREATED)
public UserDTO create(@RequestBody @Valid UserCreateDTO body) {
return service.create(body);
}
改造后的 spec 请求体:
{
"type": "object",
"properties": {
"username": { "type": "string", "description": "登录名", "example": "zhangsan", "maxLength": 32 },
"nickname": { "type": "string", "description": "昵称", "example": "张三", "maxLength": 64 },
"email": { "type": "string", "description": "邮箱", "example": "zhangsan@example.com", "format": "email" }
},
"required": ["username"]
}
要点:
| 做法 | 效果 |
|---|---|
| 用 record 而非 class | 少写 getter/setter,Jackson 与 springdoc 都原生支持 |
加 @Schema(description=...) |
文档里字段有中文说明 |
加 @Schema(example=...) |
Try it 面板自动预填示例值 |
加 @Schema(allowableValues=...) |
下拉框限定取值 |
| 加 Jakarta Validation 注解 | maxLength、format、required 自动进 schema |
| 返回值也用 DTO | 响应体有 schema,而不是 object |
校验注解之所以能自动进 schema,是因为 springdoc 内置了 Jakarta Validation 的
PropertyCustomizer,不需要额外配置。
5.2 生产环境必须关闭文档端点
/v3/api-docs 会完整暴露你的接口清单、参数名、内部路径(/admin/** 这类)。这本身就是一份攻击面地图。
关闭方式(推荐用 profile 区分环境):
# application.yml —— 开发环境
springdoc:
api-docs:
enabled: true
scalar:
enabled: true
# application-prod.yml —— 生产环境
springdoc:
api-docs:
enabled: false
scalar:
enabled: false
或者统一在代码里按环境判断:
@Bean
public OpenAPI openApi(@Value("${app.docs.enabled:false}") boolean enabled) {
if (!enabled) {
return new OpenAPI().info(new Info().title("用户服务 API").version("v1"));
}
return new OpenAPI()...;
}
关掉后 /scalar 与 /v3/api-docs 都返回 404。注意 springdoc.api-docs.enabled=false 和 scalar.enabled=false 是两个独立开关,只关一个会漏。
5.3 文档与代码同源,避免漂移
本方案的最大优势是文档不存在"忘记更新"的问题:文档是反射出来的,代码改了文档立刻跟着变。
三条实践建议:
-
把约定写进 description,而不是只写在代码注释里。代码注释 IDE 里能看,外部同事看不到;而
info.description会同时出现在 Scalar 首页、Ask AI 的上下文、以及任何导入这份 spec 的工具里。 -
CI 里跑一次 spec 快照 diff:
curl -s http://localhost:8080/v3/api-docs > openapi-current.json git diff --exit-code openapi-current.json docs/openapi.json接口有非预期变更时构建直接失败。
-
接口语义变更走 PR 评审:spec 快照的 diff 就是天然的接口变更清单。
5.4 接入鉴权
一旦文档要对外暴露(或接口本身需要鉴权),在配置类里声明安全方案:
@Bean
public OpenAPI openApi() {
return new OpenAPI()
.info(new Info().title("用户服务 API").version("v1"))
.components(new Components().addSecuritySchemes("bearerAuth",
new SecurityScheme()
.type(SecurityScheme.Type.HTTP)
.scheme("bearer")
.bearerFormat("JWT")))
.addSecurityItem(new SecurityRequirement().addList("bearerAuth"));
}
Scalar 的 Try it 面板会自动出现 Token 输入框。只想给个别接口加鉴权时,在方法上加 @SecurityRequirement(name = "bearerAuth") 即可。
5.5 常见故障排查
| 现象 | 根因 | 处理 |
|---|---|---|
启动报 ClassNotFoundException: org.springdoc... |
依赖版本与 Boot 不匹配 | 确认用 3.x(Boot 4);mvn dependency:tree 看实际引入版本 |
/scalar 404 |
UI starter 没引入 | 检查 artifactId 是否为 ...-webmvc-scalar;检查 scalar.enabled |
/v3/api-docs 404 |
spec 被关或路径被改 | 检查 springdoc.api-docs.enabled 与 springdoc.api-docs.path |
| spec 里没有某个接口 | 没有 @RestController / 被 @Hidden 标了 / 不在扫描范围内 |
确认类上有 @RestController;检查 springdoc.packages-to-scan、paths-to-match |
| 请求体是空 object | 用了 Map<String,Object> |
抽 DTO,见 5.1 |
| 参数没有出现在文档里 | 用了 @RequestParam 但没写参数名 |
加上 value = "page" 或打开 -parameters 编译参数 |
| SSE 接口在 Scalar 里没反应 | 浏览器端点对长连接的处理 | 用 curl -N 更直观 |
| 改了代码但文档没变 | spec 缓存 | springdoc.cache.disabled=true 或重启服务 |
mvn -o 离线构建失败 |
新依赖没进本地仓库 | 先联网 mvn compile 拉一次 |
六、总结
6.1 核心要点回顾
本文档系统讲解了 Spring Boot 4 下接口文档体系的搭建与使用,要点归纳如下:
- Spring Boot 4 必须用 springdoc 3.x(2.x 仅支持 Boot 3);Knife4j 全部版本均不可用。
- springdoc 3.x 官方内置 Scalar starter,spec 生成层与 UI 渲染层解耦,换 UI 只改 artifactId。
- spec 通过运行时反射生成,文档与代码天然同源,不存在"忘记更新"。
/scalar是人看的 UI,/v3/api-docs是机器读的 OpenAPI 3.1 JSON,两者同源。- Scalar 相比 Swagger UI 多出 SDK 生成、Ask AI、MCP 导出三项能力。
@Tag决定分组,@Operation/@Parameter/@Schema决定描述,方法签名决定 schema,三者职责不同。Map<String,Object>在 OpenAPI 里只能表达成空 object;要精确到字段必须用 record +@Schema。- Jakarta Validation 注解能自动进入 schema,无需额外配置。
- SSE 接口在 OpenAPI 里只体现为
text/event-stream响应,事件语义要靠 description 补充。 - 生产环境必须同时关闭
springdoc.api-docs.enabled与scalar.enabled两个开关。 - 一份 spec 可同时喂饱 Scalar、Apifox、SDK 生成、MCP、CI 契约校验五类消费端。
6.2 进阶学习路径
推荐学习资源:
- 规范:OpenAPI Specification 3.1(openapis.org),重点看 Components 与 Schema 章节。
- 官方文档:springdoc.org 的 FAQ 与 Introduction 两页,覆盖了 90% 的版本与配置问题。
- 实战:把一个
Map<String,Object>入参改成 record +@Schema,对比 spec 变化,理解 schema 的来源。
6.3 工具选型速查表
| 需求 | 推荐方案 | 说明 |
|---|---|---|
| Spring Boot 4 上展示接口 | springdoc 3.x + Scalar | 官方组合,优先选择 |
| 团队协作 + Mock + 自动化测试 | Apifox(导入 spec) | 可选叠加 |
| 前端类型安全客户端 | openapi-generator | 建议先做 DTO 改造 |
| 让 AI Agent 调用接口 | Scalar 的 MCP 导出 | 值得试 |
| 接口契约进 git 评审 | 导出 openapi.json + CI diff | 建议落地 |
| 需要 Spring Boot 3 老项目 | springdoc 2.x + Knife4j | 版本不同,勿混用 |
核心启示:接口文档不是额外写出来的一份文档,而是代码结构的另一种投影。想要一份准确的接口文档,正确的做法不是"去写文档",而是"把代码建模得足够清楚"——DTO 划清字段边界、注解说清业务语义、description 交代隐式约定。工具只是把这三样东西忠实地呈现出来。

浙公网安备 33010602011771号