10 个使用 Spring Boot 4 的开发技巧,太惊艳了!
大家好,我是Java1234_小锋老师。
Spring Boot 4 在 2025 年底正式发布,底层换成了 Spring Framework 7,很多以前要「自己造轮子」的事情,现在框架直接帮你做好了。这篇文章挑了 10 个我觉得最实用、最容易上手的技巧,每个都配了能直接抄的 demo,看完就能在项目里试。
技巧 1:API 版本管理,终于不用自己写拦截器了
以前做 REST 接口版本,常见做法是路径里加/v1、/v2,或者自己写个拦截器读 Header。Spring Boot 4 把这件事做成了「一等公民」——你在@GetMapping上标注版本号就行,框架负责路由和匹配。
第一步:开启版本解析策略
@ConfigurationpublicclassWebConfigimplementsWebMvcConfigurer{@OverridepublicvoidconfigureApiVersioning(ApiVersionConfigurerconfigurer){configurer.useRequestHeader("X-API-Version")// 从请求头读取版本号.addSupportedVersions("1","2").setDefaultVersion("1");// 没传时默认 v1}}也可以用application.yml做基础配置(复杂场景仍建议 Java 配置):
spring:mvc:apiversion:default:1supported:1,2use:header:X-API-Version第二步:在映射注解上加version属性
@RestController@RequestMapping("/api/users")publicclassUserController{// v1 版本:返回简单信息@GetMapping("/{id}")publicUserV1getUserV1(@PathVariableLongid){returnnewUserV1(id,"张三");}// v2 版本:多了邮箱字段@GetMapping(value="/{id}",version="2")publicUserV2getUserV2(@PathVariableLongid){returnnewUserV2(id,"张三","zhangsan@example.com");}}客户端调用时,带上X-API-Version: 2就能拿到 v2 的数据。同一个 URL,不同版本,代码结构清晰,不用再维护一堆if-else。
技巧 2:HTTP Service Client,写个接口就能调远程服务
Feign 好用,但有时候只想快速调一个外部 HTTP 接口,写一堆配置又嫌麻烦。Spring Boot 4 的HTTP Service Client思路很简单:定义一个 Java 接口,加上注解,Spring 自动帮你生成实现类。
// 1. 定义接口@HttpExchange(url="https://api.example.com")publicinterfaceWeatherService{@GetExchange("/weather/{city}")WeatherResponsegetWeather(@PathVariableStringcity);}// 2. 启动类或配置类上启用@SpringBootApplication@ImportHttpServices(basePackages="com.example.client")publicclassApplication{publicstaticvoidmain(String[]args){SpringApplication.run(Application.class,args);}}// 3. 像普通 Bean 一样注入使用@ServicepublicclassReportService{privatefinalWeatherServiceweatherService;publicReportService(WeatherServiceweatherService){this.weatherService=weatherService;}publicStringtodayWeather(Stringcity){returnweatherService.getWeather(city).description();}}超时、Base URL 等还可以在application.yml里统一配:
spring:http:client:service:weather-service:base-url:https://api.example.comconnect-timeout:3sread-timeout:10s以前要写RestTemplate或WebClient配置类,现在一个接口搞定,特别适合对接第三方 API 的场景。
技巧 3:虚拟线程开一行配置,HTTP 客户端也跟着受益
Java 21 引入虚拟线程后,Spring Boot 3.2 就能开启。到了 Spring Boot 4,不光 Web 请求走虚拟线程,JDK 自带的 HTTP 客户端也会自动跟着用虚拟线程,不用你再手动给HttpClient.Builder塞Executor了。
# application.ymlspring:threads:virtual:enabled:true就这么一行。开启后,Tomcat 处理请求用虚拟线程,你通过 HTTP Service Client 或 RestClient 发出去的出站请求也会复用同一套线程模型。
适合 I/O 密集型的 Web 应用——比如一个接口要调三个外部服务再汇总结果,以前线程池容易打满,现在成本低很多。当然,CPU 密集计算多的场景还是要评估,虚拟线程不是万能药。
技巧 4:RestTestClient,接口测试写法终于统一了
写 Spring Boot 测试的同学大概都经历过:MockMvc写起来啰嗦,WebTestClient又带着响应式那套概念。Spring Boot 4 新推的RestTestClient把两者优点合在一起了——链式调用、写法流畅,还不用引入 WebFlux。
切片测试(MockMvc 模式):
@SpringBootTest@AutoConfigureMockMvcclassUserControllerTest{@AutowiredRestTestClientclient;@TestvoidshouldReturnUser(){client.get().uri("/api/users/1").header("X-API-Version","1").exchange().expectStatus().isOk().expectBody().jsonPath("$.name").isEqualTo("张三");}}集成测试(真实端口模式):
@SpringBootTest(webEnvironment=SpringBootTest.WebEnvironment.RANDOM_PORT)classUserIntegrationTest{@AutowiredRestTestClientclient;@TestvoidshouldWorkOnRealServer(){client.get().uri("/api/users/1").exchange().expectStatus().isOk();}}同一个RestTestClient,Mock 和真端口两种模式切换方便,测试代码读起来也顺很多。
技巧 5:OpenTelemetry Starter,监控链路开箱即用
可观测性(Metrics + Traces)以前要引 Micrometer、OpenTelemetry SDK、各种 Exporter,配半天。Spring Boot 4 加了专用 Starter:
<!-- pom.xml --><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-opentelemetry</artifactId></dependency># application.ymlmanagement:opentelemetry:tracing:export:otlp:endpoint:http://localhost:4318/v1/tracestracing:export:enabled:true加上依赖、配好 OTLP 地址,Trace 就自动往 Jaeger、Tempo 这类后端送了。对于新项目来说,第一天就把链路追踪接上,后面排查慢接口会省很多力气。
技巧 6:API 废弃提醒,自动往响应头里塞 Sunset 信息
接口要下线,最怕客户端不知道还在调。Spring Boot 4 内置了基于 RFC 标准的废弃处理——你在配置里声明某个版本即将废弃,框架会在响应头里自动加上Deprecation、Sunset、Link等信息,提醒调用方赶紧迁移。
@ConfigurationpublicclassApiDeprecationConfigimplementsWebMvcConfigurer{@OverridepublicvoidconfigureApiVersioning(ApiVersionConfigurerconfigurer){StandardApiVersionDeprecationHandlerhandler=newStandardApiVersionDeprecationHandler();// 标记 v1 即将废弃,并设置下线时间handler.configureVersion("1").setDeprecationDate(ZonedDateTime.parse("2026-06-01T00:00:00Z")).setSunsetDate(ZonedDateTime.parse("2026-12-31T00:00:00Z")).setSunsetLink(URI.create("https://docs.example.com/migrate-v2"));configurer.useRequestHeader("X-API-Version").addSupportedVersions("1","2").setDeprecationHandler(handler);}}配合 Controller 里的版本映射:
@GetMapping("/orders")publicList<Order>listOrdersV1(){...}@GetMapping(value="/orders",version="2")publicList<OrderV2>listOrdersV2(){...}客户端收到 v1 响应后,看 Header 就知道接口在 2026 年底要停用了。以前这类逻辑得自己写 Filter,现在配置几行就搞定,对前后端协作特别友好。
技巧 7:TaskDecorator 支持多个,异步任务装饰更灵活
项目里如果有@Async或定时任务,经常需要在任务执行前后做一些通用操作——比如传递 MDC 日志上下文、注入 TraceId。以前多个TaskDecorator只能留一个,Spring Boot 4 改成自动合并多个装饰器。
@Component@Order(1)publicclassMdcTaskDecoratorimplementsTaskDecorator{@OverridepublicRunnabledecorate(Runnablerunnable){Map<String,String>context=MDC.getCopyOfContextMap();return()->{if(context!=null)MDC.setContextMap(context);try{runnable.run();}finally{MDC.clear();}};}}@Component@Order(2)publicclassTraceTaskDecoratorimplementsTaskDecorator{@OverridepublicRunnabledecorate(Runnablerunnable){StringtraceId=TraceContext.current().traceId();return()->{MDC.put("traceId",traceId);runnable.run();};}}两个装饰器都注册成 Bean,框架按@Order顺序串起来执行。异步日志终于能带上完整链路了,排查线上问题不再「断档」。
技巧 8:Redis 主从静态节点,配置一行搞定
用 Lettuce 连接 Redis 主从架构时,以前要在代码里写RedisStaticMasterReplicaConfiguration。Spring Boot 4 支持直接在配置文件里声明节点:
spring:data:redis:masterreplica:nodes:-192.168.1.10:6379# 主节点-192.168.1.11:6379# 从节点-192.168.1.12:6379适合节点固定、不走 Redis Sentinel 或 Cluster 的场景。配置简洁,也减少了启动类里的样板代码。
技巧 9:控制台日志可以单独关掉,排查问题更方便
有时候本地调试只想看文件日志,或者跑测试时控制台输出太吵。Spring Boot 4 新增了:
logging:console:enabled:false# 关闭控制台输出,文件日志照常写这个小开关看着不起眼,但在 CI 环境、Docker 容器里跑测试时很实用——日志走文件或日志采集系统,控制台干干净净。
技巧 10:升级有套路,别跳过 Spring Boot 3.5
最后这条不算「写代码技巧」,但真的很重要:从 3.x 直接跳到 4.0,坑会比想象中多。
官方建议的路径是:
Spring Boot 3.4 及以下 → 先升到 3.5 → 再升到 4.0Spring Boot 4 变动不少:Jackson 2 标记废弃、Jackson 3 成为默认;部分配置项改名(比如management.tracing.enabled→management.tracing.export.enabled);Jakarta EE 11 基线等等。
升级时可以对照官方 Migration Guide,逐项改。急不得,但值得——4.0 上面这些新能力,用上了真的会感叹「早该这样了」。
写在最后
Spring Boot 4 不是那种「换个版本号、修几个 bug」的小更新。API 版本管理、HTTP Service Client、RestTestClient、OpenTelemetry Starter……这些都是日常开发里真的会用到的东西。
建议做法:新建一个小 demo 项目,把本文技巧 1、2、4 先跑起来,感受一下写法上的变化。等有新项目或者老项目稳定期,再规划完整迁移。
如果你已经在用 Spring Boot 4,欢迎在评论区分享你觉得最「惊艳」的那个特性——每个人的业务场景不同,好用的点也可能不一样。
