Swagger(现为 OpenAPI Specification)是一个强大的 API 文档生成和测试工具,结合 Swagger UI 可以可视化展示 RESTful API 接口,极大提升开发效率和前后端协作体验。
一、核心概念
概念 | 说明 |
---|---|
Swagger | 一套用于描述、生成、调用和可视化 RESTful 风格 Web 服务的开源工具集。 |
OpenAPI Specification (OAS) | Swagger 的规范标准,定义了 API 的结构(如路径、参数、响应等)。 |
Swagger UI | 一个基于 HTML、JavaScript 和 CSS 的工具,将 OpenAPI 文档渲染成交互式网页界面。 |
Springfox / SpringDoc OpenAPI | Java 生态中用于 Spring Boot 的 Swagger 集成库。 |
注解(Annotations) | 如 @Api , @ApiOperation , @ApiModelProperty 等,用于描述接口元数据。 |
✅ 当前推荐使用
springdoc-openapi
(替代springfox
),因为其对 Spring Boot 3+、Java 17+、WebFlux 支持更好,且性能更优。
二、操作步骤(非常详细,适合新手)
我们以 springdoc-openapi
为例,集成到 Spring Boot 项目中。
✅ 步骤 1:创建 Spring Boot 项目
使用 Spring Initializr 创建项目,选择:
- Spring Boot 版本:建议 3.x(如 3.3.0)
- Language: Java 17+
- Dependencies: Spring Web
✅ 步骤 2:添加依赖(Maven 示例)
在 pom.xml
中添加:
<!-- SpringDoc OpenAPI UI -->
<dependency>
<groupId>org.springdoc</groupId>
<artifactId>springdoc-openapi-starter-webmvc-ui</artifactId>
<version>2.6.0</version> <!-- 推荐使用最新稳定版 -->
</dependency>
💡 注意:Spring Boot 3+ 使用
springdoc-openapi-starter-webmvc-ui
,旧版使用springfox-boot-starter
。
✅ 步骤 3:启动类或配置类无需额外配置(开箱即用)
默认情况下,springdoc-openapi
自动扫描所有 @RestController
和 @RequestMapping
注解。
你不需要添加 @EnableOpenApi
或配置 Docket Bean。
✅ 步骤 4:编写示例 Controller
@RestController
@RequestMapping("/api/users")
@Tag(name = "用户管理", description = "用户增删改查接口")
public class UserController {
@Operation(summary = "获取所有用户", description = "返回用户列表")
@ApiResponses(value = {
@ApiResponse(responseCode = "200", description = "成功获取用户列表",
content = @Content(schema = @Schema(implementation = User.class), mediaType = "application/json")),
@ApiResponse(responseCode = "500", description = "服务器内部错误")
})
@GetMapping
public ResponseEntity<List<User>> getAllUsers() {
List<User> users = Arrays.asList(
new User(1L, "张三", "zhangsan@example.com"),
new User(2L, "李四", "lisi@example.com")
);
return ResponseEntity.ok(users);
}
@Operation(summary = "根据ID获取用户")
@GetMapping("/{id}")
public ResponseEntity<User> getUserById(@Parameter(description = "用户ID", required = true) @PathVariable Long id) {
User user = new User(id, "测试用户", "test@example.com");
return ResponseEntity.ok(user);
}
@Operation(summary = "创建用户")
@PostMapping
public ResponseEntity<User> createUser(@io.swagger.v3.oas.annotations.parameters.RequestBody(description = "用户对象", required = true) @RequestBody User user) {
user.setId(999L);
return ResponseEntity.status(201).body(user);
}
}
✅ 步骤 5:User 实体类示例(使用 @Schema
注解)
import io.swagger.v3.oas.annotations.media.Schema;
@Schema(description = "用户信息")
public class User {
@Schema(description = "用户ID", example = "1")
private Long id;
@Schema(description = "用户名", example = "张三", requiredMode = Schema.RequiredMode.REQUIRED)
private String name;
@Schema(description = "邮箱", example = "zhangsan@example.com")
private String email;
// 构造函数、getter、setter...
}
✅ 步骤 6:启动项目并访问 Swagger UI
- 启动 Spring Boot 应用。
- 打开浏览器访问:
- Swagger UI 页面:
http://localhost:8080/swagger-ui.html
- 或新版本路径:
http://localhost:8080/swagger-ui/index.html
- Swagger UI 页面:
🎉 你会看到自动生成的 API 文档界面,可直接测试接口!
三、常见错误与解决方案
错误现象 | 原因 | 解决方案 |
---|---|---|
访问 /swagger-ui.html 报 404 |
路径变更(SpringDoc 新版本) | 改为访问 /swagger-ui/index.html |
接口未显示 | 未使用 @RestController 或未被组件扫描 |
确保类在主包路径下,或使用 @ComponentScan |
中文乱码或显示异常 | 编码问题或浏览器缓存 | 清除缓存,设置响应头 Content-Type: application/json;charset=UTF-8 |
@RequestBody 参数未显示描述 |
注解使用错误 | 使用 @io.swagger.v3.oas.annotations.parameters.RequestBody |
Spring Boot 3 + Java 17 报错 | 使用了旧版 springfox |
改用 springdoc-openapi ,避免反射问题 |
安全认证(如 Spring Security)拦截 Swagger 资源 | 静态资源未放行 | 在 SecurityConfig 中放行 /v3/api-docs/** , /swagger-ui/** , /swagger-resources/** |
四、注意事项
版本兼容性:
- Spring Boot 3.x + Java 17+ → 使用
springdoc-openapi
2.x - 避免混合使用
springfox
和springdoc
- Spring Boot 3.x + Java 17+ → 使用
生产环境安全:
- 禁止在生产环境暴露 Swagger UI!
- 使用
@Profile("dev")
或配置控制启用:# application-dev.yml springdoc: api-docs: enabled: true swagger-ui: enabled: true
# application-prod.yml springdoc: api-docs: enabled: false swagger-ui: enabled: false
注解位置:
@Tag
放在 Controller 类上@Operation
放在方法上@Parameter
用于方法参数@Schema
用于实体类字段
五、使用技巧
技巧 | 说明 |
---|---|
自定义文档标题、版本 | 在 application.yml 中配置: |
springdoc:
api-docs:
version: v1
swagger-ui:
title: 我的 API 文档
description: 提供完整的后端接口说明
version: 1.0.0
| | | 分组文档 | 多个 API 分组:
@Bean
public GroupedOpenApi publicApi() {
return GroupedOpenApi.builder()
.group("users")
.pathsToMatch("/api/users/**")
.build();
}
| |
| 添加请求头示例 | 使用 @RequestHeader
+ @Parameter
:
@Parameter(name = "Authorization", description = "JWT Token", required = true, in = ParameterIn.HEADER)
@RequestHeader("Authorization") String token
| |
| 支持文件上传 | 使用 @Schema(type = "string", format = "binary")
:
@Schema(description = "头像图片", format = "binary")
private MultipartFile avatar;
| |
六、最佳实践
- ✅ 统一文档风格:使用
@Tag
统一管理模块分类。 - ✅ 详细描述接口:每个接口使用
@Operation(summary = "...", description = "...")
。 - ✅ 标注响应状态码:使用
@ApiResponse
说明 200、400、500 等。 - ✅ 实体类字段说明:
@Schema
注解字段,增强可读性。 - ✅ 使用分组管理 API:如
user-group
,order-group
等。 - ✅ 自动化集成 CI/CD:生成 OpenAPI JSON 文件用于自动化测试或前端 Mock。
七、性能优化建议
优化点 | 说明 |
---|---|
关闭生产环境文档 | 减少扫描开销,提升启动速度 |
延迟加载文档 | 设置 springdoc.api-docs.lazy-loading=true (v2.0+ 支持) |
缓存文档 | springdoc.cache.disabled=false (默认开启) |
减少注解使用 | 避免在非必要方法上添加 Swagger 注解 |
异步生成文档 | 不影响主流程,文档在后台生成 |
八、扩展功能(高级)
导出 OpenAPI JSON/YAML:
- 访问:
http://localhost:8080/v3/api-docs
(JSON) - 或
http://localhost:8080/v3/api-docs.yaml
- 访问:
集成 Spring Security:
- 放行 Swagger 资源路径
- 添加 JWT 认证支持(在 Swagger UI 中添加
Authorize
按钮)
自定义 Swagger UI 页面:
- 替换
index.html
或使用springdoc.swagger-ui.path
自定义路径
- 替换
与前端 Mock 工具集成:
- 使用 OpenAPI 文件生成 Mock Server(如 Prism、Stoplight)
九、总结
项目 | 推荐方案 |
---|---|
工具选择 | springdoc-openapi (非 springfox ) |
注解标准 | OpenAPI 3.x 注解(io.swagger.v3.oas.annotations ) |
生产安全 | 关闭文档生成与 UI 显示 |
文档质量 | 使用 @Tag , @Operation , @Schema 提升可读性 |
性能 | 启用缓存、延迟加载、按需分组 |
✅ 一句话总结:
使用 springdoc-openapi
+ OpenAPI 3 注解,开箱即用生成美观、交互式 API 文档,提升开发协作效率,但务必在生产环境关闭!