Skip to content

API 版本管理 (API Versioning)

Spring MVC 提供了对 API 版本管理的内置支持,帮助开发者平滑地进行接口升级和多版本并存。

核心策略

API 版本管理主要通过 ApiVersionStrategy 进行调度,它涵盖了版本的解析、解析、验证以及弃用提醒。

1. 版本解析 (Resolver)

你可以配置从何处获取版本信息:

  • Header: 例如 X-API-Version: 1.2
  • Query Parameter: 例如 /api/users?version=1.2
  • Media Type: 在 Accept 标头中,例如 application/vnd.example.v1.2+json
  • URL Path: 例如 /v1.2/users

2. 映射请求

你可以直接在 @RequestMapping 或其变体中使用 version 属性。

java
@RestController
@RequestMapping("/users")
public class UserController {

    @GetMapping(path = "/{id}", version = "1.0")
    public UserV1 getUserV1(@PathVariable String id) {
        // ...
    }

    @GetMapping(path = "/{id}", version = "2.0")
    public UserV2 getUserV2(@PathVariable String id) {
        // ...
    }
}
kotlin
@RestController
@RequestMapping("/users")
class UserController {

    @GetMapping("/{id}", version = "1.0")
    fun getUserV1(@PathVariable id: String): UserV1 {
        // ...
    }

    @GetMapping("/{id}", version = "2.0")
    fun getUserV2(@PathVariable id: String): UserV2 {
        // ...
    }
}

弃用处理 (Deprecation)

Spring 支持根据 RFC 9745 和 RFC 8594 发送 DeprecationSunset 响应头,提醒客户端该版本即将停用。


补充教学

1. 语义化版本解析 (Semantic Parsing)

默认情况下,Spring 采用语义化版本(Semantic Versioning)解析。它会将版本号拆分为 major, minor, patch 三部分进行比较。

  • 匹配规则支持固定版本(如 "1.2")或基准版本(如 "1.2+" 表示 1.2 及以上版本)。

2. 选择合适的解析位置

  • URL Path: 最直观,利于浏览器缓存区分,但会改变基础路径。
  • Accept Header: 遵循 REST 约定,路径保持洁净,但调试相对麻烦。
  • Custom Header: 灵活性最高且不破坏现有标准。

3. 未匹配版本的处理

如果请求了一个不支持的版本:

  • 默认抛出 InvalidApiVersionException (返回 400 Bad Request)。
  • 你可以在配置中设置一个默认版本,当请求未提供版本时自动回退。

Based on Spring Framework.