10 个使用 Spring Boot 4 的开发技巧,太惊艳了!

📅 2026/6/29 23:32:00
10 个使用 Spring Boot 4 的开发技巧,太惊艳了!
大家好我是Java1234_小锋老师。Spring Boot 4 在 2025 年底正式发布底层换成了 Spring Framework 7很多以前要「自己造轮子」的事情现在框架直接帮你做好了。这篇文章挑了 10 个我觉得最实用、最容易上手的技巧每个都配了能直接抄的 demo看完就能在项目里试。技巧 1API 版本管理终于不用自己写拦截器了以前做 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属性RestControllerRequestMapping(/api/users)publicclassUserController{// v1 版本返回简单信息GetMapping(/{id})publicUserV1getUserV1(PathVariableLongid){returnnewUserV1(id,张三);}// v2 版本多了邮箱字段GetMapping(value/{id},version2)publicUserV2getUserV2(PathVariableLongid){returnnewUserV2(id,张三,zhangsanexample.com);}}客户端调用时带上X-API-Version: 2就能拿到 v2 的数据。同一个 URL不同版本代码结构清晰不用再维护一堆if-else。技巧 2HTTP Service Client写个接口就能调远程服务Feign 好用但有时候只想快速调一个外部 HTTP 接口写一堆配置又嫌麻烦。Spring Boot 4 的HTTP Service Client思路很简单定义一个 Java 接口加上注解Spring 自动帮你生成实现类。// 1. 定义接口HttpExchange(urlhttps://api.example.com)publicinterfaceWeatherService{GetExchange(/weather/{city})WeatherResponsegetWeather(PathVariableStringcity);}// 2. 启动类或配置类上启用SpringBootApplicationImportHttpServices(basePackagescom.example.client)publicclassApplication{publicstaticvoidmain(String[]args){SpringApplication.run(Application.class,args);}}// 3. 像普通 Bean 一样注入使用ServicepublicclassReportService{privatefinalWeatherServiceweatherService;publicReportService(WeatherServiceweatherService){this.weatherServiceweatherService;}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 密集计算多的场景还是要评估虚拟线程不是万能药。技巧 4RestTestClient接口测试写法终于统一了写 Spring Boot 测试的同学大概都经历过MockMvc写起来啰嗦WebTestClient又带着响应式那套概念。Spring Boot 4 新推的RestTestClient把两者优点合在一起了——链式调用、写法流畅还不用引入 WebFlux。切片测试MockMvc 模式SpringBootTestAutoConfigureMockMvcclassUserControllerTest{AutowiredRestTestClientclient;TestvoidshouldReturnUser(){client.get().uri(/api/users/1).header(X-API-Version,1).exchange().expectStatus().isOk().expectBody().jsonPath($.name).isEqualTo(张三);}}集成测试真实端口模式SpringBootTest(webEnvironmentSpringBootTest.WebEnvironment.RANDOM_PORT)classUserIntegrationTest{AutowiredRestTestClientclient;TestvoidshouldWorkOnRealServer(){client.get().uri(/api/users/1).exchange().expectStatus().isOk();}}同一个RestTestClientMock 和真端口两种模式切换方便测试代码读起来也顺很多。技巧 5OpenTelemetry Starter监控链路开箱即用可观测性Metrics Traces以前要引 Micrometer、OpenTelemetry SDK、各种 Exporter配半天。Spring Boot 4 加了专用 Starter!-- pom.xml --dependencygroupIdorg.springframework.boot/groupIdartifactIdspring-boot-starter-opentelemetry/artifactId/dependency# application.ymlmanagement:opentelemetry:tracing:export:otlp:endpoint:http://localhost:4318/v1/tracestracing:export:enabled:true加上依赖、配好 OTLP 地址Trace 就自动往 Jaeger、Tempo 这类后端送了。对于新项目来说第一天就把链路追踪接上后面排查慢接口会省很多力气。技巧 6API 废弃提醒自动往响应头里塞 Sunset 信息接口要下线最怕客户端不知道还在调。Spring Boot 4 内置了基于 RFC 标准的废弃处理——你在配置里声明某个版本即将废弃框架会在响应头里自动加上Deprecation、Sunset、Link等信息提醒调用方赶紧迁移。ConfigurationpublicclassApiDeprecationConfigimplementsWebMvcConfigurer{OverridepublicvoidconfigureApiVersioning(ApiVersionConfigurerconfigurer){StandardApiVersionDeprecationHandlerhandlernewStandardApiVersionDeprecationHandler();// 标记 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)publicListOrderlistOrdersV1(){...}GetMapping(value/orders,version2)publicListOrderV2listOrdersV2(){...}客户端收到 v1 响应后看 Header 就知道接口在 2026 年底要停用了。以前这类逻辑得自己写 Filter现在配置几行就搞定对前后端协作特别友好。技巧 7TaskDecorator 支持多个异步任务装饰更灵活项目里如果有Async或定时任务经常需要在任务执行前后做一些通用操作——比如传递 MDC 日志上下文、注入 TraceId。以前多个TaskDecorator只能留一个Spring Boot 4 改成自动合并多个装饰器。ComponentOrder(1)publicclassMdcTaskDecoratorimplementsTaskDecorator{OverridepublicRunnabledecorate(Runnablerunnable){MapString,StringcontextMDC.getCopyOfContextMap();return()-{if(context!null)MDC.setContextMap(context);try{runnable.run();}finally{MDC.clear();}};}}ComponentOrder(2)publicclassTraceTaskDecoratorimplementsTaskDecorator{OverridepublicRunnabledecorate(Runnablerunnable){StringtraceIdTraceContext.current().traceId();return()-{MDC.put(traceId,traceId);runnable.run();};}}两个装饰器都注册成 Bean框架按Order顺序串起来执行。异步日志终于能带上完整链路了排查线上问题不再「断档」。技巧 8Redis 主从静态节点配置一行搞定用 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.enabledJakarta EE 11 基线等等。升级时可以对照官方 Migration Guide逐项改。急不得但值得——4.0 上面这些新能力用上了真的会感叹「早该这样了」。写在最后Spring Boot 4 不是那种「换个版本号、修几个 bug」的小更新。API 版本管理、HTTP Service Client、RestTestClient、OpenTelemetry Starter……这些都是日常开发里真的会用到的东西。建议做法新建一个小 demo 项目把本文技巧 1、2、4 先跑起来感受一下写法上的变化。等有新项目或者老项目稳定期再规划完整迁移。如果你已经在用 Spring Boot 4欢迎在评论区分享你觉得最「惊艳」的那个特性——每个人的业务场景不同好用的点也可能不一样。