Swagger 核心组件
Editor、UI、Codegen、Hub 各自做什么,以及 Java/Spring 生态里的 springdoc。
Key PointsEditor 写规范、UI 渲染文档、Codegen 生成代码、Hub 托管规范;Spring 项目用 springdoc 从注解直接产出规范。
四个核心工具
| Tool | Job | Typical use |
|---|---|---|
| Swagger Editor | Write & validate the spec | Browser IDE with live preview |
| Swagger UI | Render the spec as a doc site | /swagger-ui in your service |
| Swagger Codegen | Generate clients and servers | CI job, or openapi-generator |
| Swagger Hub | Host, version and collaborate | Team design-first workflow |
本地跑一个 Editor
Bash
docker run -d -p 8080:8080 \
-e SWAGGER_JSON=/spec/openapi.yaml \
-v "$PWD:/spec" \
swaggerapi/swagger-ui
# 打开 http://localhost:8080Java / Spring 生态:springdoc
Spring Boot projects rarely hand-write YAML: annotations describe the API and springdoc generates /v3/api-docs at runtime, which Swagger UI reads. The spec cannot drift from the code.
XML
<dependency>
<groupId>org.springdoc</groupId>
<artifactId>springdoc-openapi-starter-webmvc-ui</artifactId>
<version>2.6.0</version>
</dependency>Java
@Operation(summary = "查询单个用户")
@GetMapping("/users/{id}")
public User get(@Parameter(description = "用户 ID") @PathVariable Long id) {
return userService.get(id);
}The Swagger 2 era
springfox is unmaintained; use springdoc-openapi for new projects. Their annotations are not interchangeable, so migrate them together.其他语言的一行接入
- Python / FastAPI —
app = FastAPI(),/docs自动可用 - Node.js / Express —
swagger-ui-express+swagger-jsdoc - Go —
swag init从注释生成docs/,再挂gin-swagger - PHP / Laravel —
l5-swagger读注解生成
四个核心工具
| 工具 | 职责 | 典型用法 |
|---|---|---|
| Swagger Editor | 编写与校验规范 | 浏览器 IDE,实时预览 |
| Swagger UI | 把规范渲染成文档站 | 服务里的 /swagger-ui |
| Swagger Codegen | 生成客户端与服务端骨架 | CI 任务或 openapi-generator |
| Swagger Hub | 托管、版本与协作 | 团队设计先行流程 |
本地跑一个 Editor
Bash
docker run -d -p 8080:8080 \
-e SWAGGER_JSON=/spec/openapi.yaml \
-v "$PWD:/spec" \
swaggerapi/swagger-ui
# 打开 http://localhost:8080Java / Spring 生态:springdoc
Spring Boot 项目通常不手写 YAML,而是用注解描述,由 springdoc 在运行时生成 /v3/api-docs,Swagger UI 直接读它。这样规范和代码天然一致。
XML
<dependency>
<groupId>org.springdoc</groupId>
<artifactId>springdoc-openapi-starter-webmvc-ui</artifactId>
<version>2.6.0</version>
</dependency>Java
@Operation(summary = "查询单个用户")
@GetMapping("/users/{id}")
public User get(@Parameter(description = "用户 ID") @PathVariable Long id) {
return userService.get(id);
}Swagger 2 时代的
springfox 已停止维护,新项目用 springdoc-openapi。二者注解不通用,迁移时要一起改。其他语言的一行接入
- Python / FastAPI ——
app = FastAPI(),/docs自动可用 - Node.js / Express ——
swagger-ui-express+swagger-jsdoc - Go ——
swag init从注释生成docs/,再挂gin-swagger - PHP / Laravel ——
l5-swagger读注解生成