Swagger 笔记
一、Swagger 是什么?
Swagger 是一套围绕 OpenAPI 规范 构建的开源工具集,主要用于 API 的设计、构建、文档化和测试。其核心组件包括:
- Swagger UI:可视化 API 文档界面,支持在线调试接口
- Swagger Editor:基于浏览器的 API 设计工具
- Swagger Codegen:根据 API 定义生成客户端/服务端代码
二、Swagger 的核心价值
场景 | 作用 |
---|---|
前后端协作 | 提供实时更新的 API 文档,减少沟通成本 |
接口调试 | 通过 Swagger UI 直接发送请求,验证接口逻辑 |
自动化测试 | 结合测试框架生成测试用例 |
API 管理 | 记录接口版本、参数规则等元数据 |
三、Spring Boot 集成 Swagger 注解
1. 基础配置步骤
1️⃣ 添加依赖(Maven):
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-boot-starter</artifactId>
<version>3.0.0</version>
</dependency>
2️⃣ 配置类示例:
@Configuration
@EnableSwagger2
public class SwaggerConfig {
@Bean
public Docket api() {
return new Docket(DocumentationType.SWAGGER_2)
.select()
.apis(RequestHandlerSelectors.basePackage("com.example.controller"))
.paths(PathSelectors.any())
.build();
}
}
2. 核心注解详解
① @Api
- 类级别
@Api(tags = "用户管理模块",
description = "包含用户注册、登录、信息查询等功能")
@RestController
@RequestMapping("/users")
public class UserController { ... }
参数说明:
tags
:接口分组名称(建议英文)description
:模块功能描述
② @ApiOperation
- 方法级别
@ApiOperation(
value = "创建新用户",
notes = "需提供用户名、密码等基本信息",
response = UserVO.class
)
@PostMapping
public ResponseEntity<UserVO> createUser(@RequestBody UserDTO dto) { ... }
参数说明:
value
:接口简要说明(显示在接口列表)notes
:详细说明(点击接口后展开)response
:定义返回对象类型
③ @ApiModel
- 数据模型类
@ApiModel(description = "用户数据传输对象")
public class UserDTO {
@ApiModelProperty(value = "用户名", required = true, example = "john_doe")
private String username;
@ApiModelProperty(value = "密码", required = true, example = "P@ssw0rd!", hidden = true)
private String password;
}
参数说明:
required
:是否必填(默认false
)example
:示例值hidden
:隐藏字段(不显示在文档)
④ @ApiParam
- 参数级别
@GetMapping("/{id}")
public UserVO getUser(
@ApiParam(value = "用户ID", required = true, example = "123")
@PathVariable Long id) { ... }
四、补充说明
-
版本兼容性:
SpringFox 3.x 需要 Spring Boot 2.6+,旧项目建议使用 2.9.2 版本 -
生产环境安全:
通过@Profile("dev")
限制 Swagger 仅在开发环境启用 -
扩展文档:
使用@ApiImplicitParams
描述非实体类参数 -
全局配置:
通过Docket.globalResponseMessage()
定义统一响应格式
五、最佳实践
- 文档规范:要求所有接口必须添加
@ApiOperation
和@ApiModelProperty
- 参数验证:结合
@NotNull
等校验注解与@ApiModelProperty(required=true)
- 版本控制:通过
Docket.groupName()
实现多版本 API 共存
通过合理使用 Swagger 注解,可显著提升 API 的可维护性和团队协作效率。