JOURNAL / WORDS & IDEAS

Swagger 2 与 Springfox:旧项目接入笔记

记录旧版 Spring Boot 项目使用 Springfox 的配置与注解,并说明升级边界。

阅读设置

注:Springfox / Swagger 2 的接入示例不适用于所有 Spring Boot 版本。Boot 3 常用的 springdoc 入口是对应版本的 starter-webmvc-ui 或 WebFlux starter,不能直接照搬 Boot 2 的依赖。

这是一份基于 demo-swagger 项目的 Swagger 2 (Springfox) 核心使用笔记。这份笔记涵盖了从配置、注解到最佳实践的所有关键点,适合快速回顾。


1. 核心概念

  • 作用:自动生成 RESTful API 文档,提供在线调试界面(Swagger UI)。
  • 本质:通过扫描 Controller 层的注解,生成符合 OpenAPI 规范的 JSON,并渲染成 HTML 页面。
  • 依赖:通常引入 springfox-swagger2 和 springfox-swagger-ui。

2. 常用注解速查表

A. 类级别 (Controller)

注解 属性 说明
@Api tags 分组名称。在 Swagger UI 左侧菜单显示的大标题。
description 对该模块的简要描述。
value 旧版本属性,现多用 tags 代替。

B. 方法级别 (Method)

注解 属性 说明
@ApiOperation value 接口简述。显示在接口标题处,必填。
notes 详细描述。显示在展开后的备注区。
httpMethod 指定 HTTP 方法 (GET/POST…),通常可省略,由 @GetMapping 等推断。

C. 参数级别 (Param) - 重点

用于描述非 @RequestBody 的参数(如 Query, Path, Header)。

注解 属性 说明
@ApiImplicitParams - 包裹多个 @ApiImplicitParam 的容器。
@ApiImplicitParam name 参数名。必须与 Java 方法参数名一致。
value 参数说明。前端看到的提示文字。
required true/false。是否必填。
paramType 参数位置。 query: URL问号后 (?id=1) path: URL路径 (/user/1) header: 请求头 body: 请求体 (JSON) form: 表单提交
dataType 数据类型。 String, int, long, double, boolean 等。建议使用常量类避免拼写错误。
defaultValue 默认值。Swagger UI 输入框会预填此值,方便测试。

D. 实体类级别 (Model)

用于描述 @RequestBody 或返回对象中的字段。

注解 属性 说明
@ApiModel value / description 类的描述。
@ApiModelProperty value 字段说明。
example 示例值。
required 是否必填。
hidden true 则不在文档中显示该字段。

3. 代码实战示例

场景一:GET 请求 (Query & Path)

@GetMapping("/{id}")
@ApiOperation(value = "根据ID查询用户")
@ApiImplicitParams({
    @ApiImplicitParam(
        name = "id",
        value = "用户主键",
        dataType = DataType.LONG, // 使用常量
        paramType = ParamType.PATH, // 路径参数
        required = true
    )
})
public ApiResponse<User> get(@PathVariable Long id) { ... }

场景二:POST 请求 (JSON Body)

注意:对于 @RequestBody 对象,不需要写 @ApiImplicitParam。Swagger 会自动解析对象内部的 @ApiModelProperty。

@PostMapping
@ApiOperation(value = "新增用户")
public ApiResponse<Void> add(@RequestBody User user) { ... }

// User 类内部:
@Data
@ApiModel("用户实体")
public class User {
    @ApiModelProperty("用户名")
    private String name;

    @ApiModelProperty(value = "年龄", example = "18")
    private Integer age;
}

场景三:文件上传

@PostMapping("/upload")
@ApiOperation("文件上传")
@ApiImplicitParam(name = "file", value = "文件对象", paramType = ParamType.FORM, dataType = "__file")
public String upload(@RequestParam("file") MultipartFile file) { ... }
  • 注:dataType = "__file" 是 Swagger 2 识别文件上传的特殊写法(不同版本可能略有差异,有时只需标注 paramType = "form")。

4. 最佳实践与避坑指南

✅ 推荐做法

  1. 使用常量类:如 Demo 中的 ParamType 和 DataType,防止手误拼写 "qurey" 或 "Int"。
  2. 统一响应封装:如 ApiResponse,让 Swagger 能清晰展示通用的返回结构(code, message, data)。
  3. 分组管理:如果接口很多,利用 @Api(tags = "v1.0-用户模块") 进行清晰分组。

❌ 常见误区

  1. 过度注解:@RequestBody 的对象内部已经用了 @ApiModelProperty,就不要再在 Controller 方法上写 @ApiImplicitParam 了,否则会导致文档重复或冲突。
  2. 生产环境暴露:Swagger 包含敏感接口信息,严禁在生产环境开启。
    • 解决方案:通过 @Profile({"dev", "test"}) 控制 Swagger 配置类的加载,或在 Security 中拦截 /swagger-ui.html 路径。
  3. 忽略默认值:对于测试友好的接口,尽量设置 defaultValue,这样前端在 UI 上点击 “Try it out” 时可以直接执行,无需手动输入。

5. 进阶:Swagger 2 vs OpenAPI 3 (SpringDoc)

  • Swagger 2 (Springfox): 你当前 Demo 使用的版本。稳定,但已停止更新多年。对 Spring Boot 2.6+ 支持不佳(需配置路径匹配策略)。
  • OpenAPI 3 (SpringDoc): 新一代标准。
    • 依赖:springdoc-openapi-ui。
    • 注解变化:
      • @Api -> @Tag
      • @ApiOperation -> @Operation
      • @ApiImplicitParam -> @Parameter
    • 建议:如果是新项目,直接上 SpringDoc;如果是老项目维护,继续使用 Springfox。

一句话总结: Swagger 是后端给前端写的“情书”,注解写得越详细,前端联调时的“误会”就越少。保持文档与代码同步,是专业开发者的基本素养。