
Spring 官方已经发布了 Spring Boot 4.0 的快照版本,内置 Spring Framework 7.0。Spring Framework 7.0 引入了对 API 版本控制的原生支持,为服务器端和客户端应用程序提供了强大的工具,以高效处理版本特定的路由和请求。
API 版本控制是现代 Web 开发中的关键实践,它允许开发者在不破坏现有客户端的情况下管理 API 的演进和变更,确保向后兼容性的同时引入新功能。
基础使用:RequestMapping version 属性
Spring Framework 7.0 在 @RequestMapping 及其变体注解中新增了 version 属性,让版本控制变得更加简洁和直观。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
| @RequestMapping @RestController public class DemoController {
@GetMapping(version = "1") public String version1() { return "API Version 1.0.0"; }
@GetMapping(version = "2") public String version2() { return "API Version 2.0.0"; } @GetMapping(version = {"1", "2"}) public String commonEndpoint() { return "支持多个版本的通用端点"; } }
|

通过实现 WebMvcConfigurer 接口并重写 configureApiVersioning 方法,可以自定义版本解析策略。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
| @Configuration public class WebConfiguration implements WebMvcConfigurer {
@Override public void configureApiVersioning(ApiVersionConfigurer configurer) { configurer.useRequestParam("version"); } }
|
常见的版本控制策略
- 请求参数方式:
?version=1
- 请求头方式:
API-Version: 1
- 路径变量方式:
/api/v1/users
- Accept 头方式:
Accept: application/vnd.api+json;version=1
调用测试
使用请求参数进行版本控制的测试示例:
1 2 3 4 5 6 7 8 9 10
| curl "http://localhost:8080/?version=1"
curl "http://localhost:8080/?version=2"
curl "http://localhost:8080/"
|
高级配置:自定义版本解析器
对于复杂的业务场景,可以实现自定义的版本解析逻辑:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26
| @Configuration public class WebConfiguration implements WebMvcConfigurer {
@Override public void configureApiVersioning(ApiVersionConfigurer configurer) { configurer.useVersionResolver(new ApiVersionResolver() { @Override public @Nullable String resolveVersion(HttpServletRequest request) { String userAgent = request.getHeader("User-Agent"); if (userAgent != null && userAgent.contains("mobile")) { return "mobile"; } String clientIp = getClientIp(request); if (isTestEnvironment(clientIp)) { return "beta"; } return "1"; } }); } }
|
总结

通过 Spring Boot 4.0 的原生版本控制支持,开发者可以更优雅地管理API的演进,提升系统的可维护性和用户体验。