
Spring Boot 4.2.0 已经发布,并可以从 Maven Central 直接拉取。

这个版本属于 Spring Boot 4.x 系列,底层基于 Spring Framework 7.1。它的升级重点不只是“版本号变大”,而是围绕消息协议、可观测性、安全连接、构建效率和 API 现代化做了明显增强。
对于 Java 后端开发者来说,4.2 值得重点关注。
一、先建立一个整体认知
Spring Boot 的核心价值,一直是“约定优于配置”。

它通过 Starter、自动配置、内嵌服务器和 Actuator,把 Java Web 项目从复杂的 XML 配置里解放出来。开发者不用再把大量时间花在框架搭建上,而是可以更专注业务代码。
从 2025 年 11 发布的 4.0 开始,Spring Boot 进入了基于 Spring Framework 7 的新阶段:
- 代码库全面模块化;
- 引入 JSpecify 空安全注解;
- Java 17 起步;
- 对 Java 25 提供更好支持。
4.2 是这条线上的第三个版本。官方保持约半年一个小版本的节奏,本次发布也带动了周边生态同步升级,包括:
- Spring Security 7.2;
- Spring Data 2026.1;
- Spring Kafka 4.2;
- Micrometer 1.18;
- Hibernate 7.4;
- JUnit Jupiter 6.1。
可以理解为一次“全家桶换新”。
想尝鲜的话,先修改父版本即可:
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>4.2.0</version>
</parent>
二、一图看懂 4.2 的亮点
| 方向 | 一句话说明 |
|---|---|
| 消息 | 新增 AMQP 1.0 支持,既有通用版,也有 RabbitMQ 定制版 |
| 可观测性 | 可选启用 OpenTelemetry 语义规范,OTLP 配置统一管理 |
| 安全 | LDAP 客户端和内嵌 LDAP 服务器都支持 SSL Bundle |
| 构建 | Buildpacks 构建缓存可存入镜像仓库,默认基础镜像升级到 Ubuntu 26.04 |
| 性能 | 可执行 jar 启动更快,内存分配更少 |
| API | RestTemplate、TestRestTemplate 等配套设施被标记为废弃 |
三、AMQP 1.0 正式登场
这是 4.2 最值得关注的变化之一。
以前提到 Spring Boot 集成 AMQP,很多人默认想到的是 RabbitMQ 经典的 AMQP 0.9.1。
但 AMQP 1.0 才是 OASIS 和 ISO 认证的国际标准,ActiveMQ Artemis、Azure Service Bus、Solace 等中间件都支持它。RabbitMQ 4.x 也把 AMQP 1.0 提升为核心协议。
Spring Boot 4.2 提供了两种支持:
| 方案 | 适用场景 |
|---|---|
| 通用 AMQP 1.0 | 连接任何兼容 AMQP 1.0 的消息中间件 |
| RabbitMQ AMQP 1.0 | 针对 RabbitMQ 做了更多定制 |
这里有一个重要的命名变化:
spring-boot-starter-amqp:现在对应通用 AMQP 1.0;spring-boot-starter-rabbitmq:承载原来的 AMQP 0.9.1 支持。
如果项目只针对 RabbitMQ,可以直接选择 RabbitMQ 专属 Starter:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-amqp-rabbitmq</artifactId>
</dependency>
配置示例:
spring:
amqp:
rabbitmq:
host: localhost
port: 5672
username: admin
password: "123456"
注意:用户名和密码不再有默认值,不配会按匿名访问处理。
消息生产者:
@Service
public class OrderMessageProducer {
private static final Logger log = LoggerFactory.getLogger(OrderMessageProducer.class);
private final RabbitAmqpTemplate rabbitAmqpTemplate;
public OrderMessageProducer(RabbitAmqpTemplate rabbitAmqpTemplate) {
this.rabbitAmqpTemplate = rabbitAmqpTemplate;
}
public void sendOrderCreated(String orderNo) {
rabbitAmqpTemplate.convertAndSend("order.exchange", "order.created", orderNo)
.thenAccept(success -> log.info("订单消息发送结果:{},订单号:{}", success, orderNo));
}
}
消息消费者:
@Component
public class OrderMessageListener {
private static final Logger log = LoggerFactory.getLogger(OrderMessageListener.class);
@RabbitListener(queues = "order.created.queue")
public void onOrderCreated(String orderNo) {
log.info("收到订单创建消息,开始处理订单:{}", orderNo);
}
}
小提示:AMQP 1.0 的健康检查指标 key 是 amqprabbit,和旧的 rabbit 可以共存。不需要时可以关闭:
management:
health:
amqprabbit:
enabled: false
四、可观测性再进一步:拥抱 OpenTelemetry 规范
这是很多团队会感兴趣的改进。
一个应用通常需要向外输出三类数据:
- Traces:链路追踪;
- Metrics:指标;
- Logs:日志。
理想情况下,这些数据应该通过统一协议发送到 OpenTelemetry Collector,再分发到不同监控系统。
Spring Boot 4.2 在这条链路上做了三个重要改进。
1. 可选启用 OpenTelemetry 语义规范
以前 Micrometer 有自己的指标命名习惯,接入 OpenTelemetry 生态时经常需要额外映射。
4.2 可以直接启用 OpenTelemetry 稳定版语义规范,让指标名、标签名更符合统一标准。
2. OTLP 配置统一管理
链路、日志、指标三个导出器的配置,以前可能要分别写。现在可以统一放到 management.opentelemetry.otlp 下。
使用 HTTP 传输时,框架还会自动补上 /v1/traces、/v1/logs、/v1/metrics 路径。
3. MDC traceId 字段名可自定义
很多日志平台约定使用 trace_id 而不是 traceId。以前改起来比较麻烦,现在可以直接配置:
management:
observations:
conventions: open-telemetry
opentelemetry:
otlp:
endpoint: http://otel-collector:4318
compression: gzip
headers:
x-api-key: demo-key
tracing:
sampling:
probability: 1.0
mdc:
trace-id-key: trace_id
span-id-key: span_id
baggage:
tag-fields: tenant-id
开启 OpenTelemetry 规范后,自定义指标名配置可能不再生效。迁移前一定要检查监控看板。
五、LDAP 终于支持 SSL Bundle
企业内部系统经常要对接 LDAP 或 AD 域账号。
以前如果要走 LDAPS 加密连接,通常需要自己写 SocketFactory、处理证书,过程比较繁琐。
Spring Boot 3.1 引入的 SSL Bundle 已经覆盖了 Web 服务器、Redis、Kafka 等组件。4.2 把 LDAP 也纳入进来了。
配置示例:
spring:
ssl:
bundle:
jks:
ldap-bundle:
truststore:
location: classpath:ldap-truststore.p12
password: "123456"
type: PKCS12
ldap:
urls: ldaps://ldap.example.com:636
base: dc=example,dc=com
username: cn=admin,dc=example,dc=com
password: "123456"
ssl:
bundle: ldap-bundle
业务代码不用关心加密细节,直接使用 LdapTemplate 即可:
@Service
public class LdapUserService {
private final LdapTemplate ldapTemplate;
public LdapUserService(LdapTemplate ldapTemplate) {
this.ldapTemplate = ldapTemplate;
}
public List<String> findDisplayNames(String uid) {
return ldapTemplate.search(
LdapQueryBuilder.query().where("uid").is(uid),
attrs -> (String) attrs.get("cn").get());
}
}
还有两个实用改进:
- 不需要 Bundle 时,可直接开启 JDK 默认证书:
spring.ldap.ssl.enabled=true; - 内嵌 LDAP 服务器也支持 LDAPS,测试和生产配置不再容易冲突。
六、启动更快了,CI 构建也更快
1. 可执行 jar 启动提速
Spring Boot 的 fat jar 内部嵌套了很多 jar。以前每次查找类或资源,都可能重复打开连接,开销比较明显。
4.2 优化了嵌套 jar 查找、压缩条目读取和资源缓存,启动速度和启动期间内存分配都有改善。
这种优化不需要改代码,升级版本即可受益。依赖越多的项目,感受可能越明显。
2. Buildpacks 构建缓存可共享
使用 spring-boot:build-image 的团队可能遇到过一个问题:
本地构建很快,但 CI 每次都像第一次一样慢。
原因是构建缓存默认存在 Docker 本地卷里,而 CI 节点往往用完即删。
4.2 支持把 buildCache 推送到镜像仓库,让多个 CI 节点共享同一份热缓存。
Maven 配置:
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<configuration>
<image>
<buildCache>
<image>
<name>registry.example.com/cache-${project.artifactId}:latest</name>
</image>
</buildCache>
</image>
</configuration>
</plugin>
Gradle 配置:
bootBuildImage {
buildCache {
image {
name = "registry.example.com/cache-${rootProject.name}:latest"
}
}
}
注意:目前只有 buildCache 支持镜像缓存。需要认证时,要提前配置好 docker.publishRegistry 凭据。
另外,Buildpacks 默认基础镜像已从 Ubuntu 24.04 升级到 Ubuntu 26.04。
七、@DefaultValue 支持占位符
在使用构造器绑定配置类时,默认值现在可以引用其他配置。
例如,支付回调地址可以默认跟随站点域名:
@ConfigurationProperties("app.pay")
public record PayProperties(
@DefaultValue("${app.site-url}/api/pay/notify")
String notifyUrl,
@DefaultValue("30s")
Duration timeout
) {}
配置:
app:
site-url: [https://shop.example.com](https://shop.example.com)
如果不配置 app.pay.notify-url,会自动得到:
[https://shop.example.com/api/pay/notify](https://shop.example.com/api/pay/notify)
启用方式:
@ConfigurationPropertiesScan
或:
@EnableConfigurationProperties(PayProperties.class)
八、其他值得关注的改进
1. Caffeine 异步缓存
spring:
cache:
caffeine:
cache-mode: async
2. Kafka 独立 Admin 配置
可以分别为模板和监听器配置独立的 KafkaAdmin。
3. GraphQL HTTP 方法可配置
spring:
graphql:
http:
methods:
- POST
- GET
4. Maven 插件新增 testClasspath
替代旧的 useTestClasspath,可选值包括 off、dependencies、all。
5. 属性迁移器可配置为“失败即停”
适合在 CI 中阻断过时配置。
6. SBOM 导出更方便
使用 jarmode=tools 的 sbom 命令,可以直接导出 jar 包内的软件物料清单。
九、和 RestTemplate 说再见
这是对老项目影响最大的变化之一。
Spring Framework 7.1 已经把 RestTemplate 标记为“计划移除”。Spring Boot 4.2 也同步废弃了:
RestTemplate;RestTemplateBuilder;RestTemplateCustomizer;TestRestTemplate。
目前代码还能运行,但已经到了该迁移的时候。
迁移前
@Service
public class WeatherClient {
private final RestTemplate restTemplate;
public WeatherClient(RestTemplateBuilder builder) {
this.restTemplate = builder.rootUri("[https://api.example.com](https://api.example.com)").build();
}
public WeatherInfo today(String city) {
return restTemplate.getForObject("/weather?city={city}", WeatherInfo.class, city);
}
}
迁移后
@Service
public class WeatherClient {
private final RestClient restClient;
public WeatherClient(RestClient.Builder builder) {
this.restClient = builder.baseUrl("[https://api.example.com](https://api.example.com)").build();
}
public WeatherInfo today(String city) {
return restClient.get()
.uri("/weather?city={city}", city)
.retrieve()
.body(WeatherInfo.class);
}
}
测试代码建议从 TestRestTemplate 迁移到 RestTestClient:
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
@AutoConfigureRestTestClient
class UserControllerTest {
@Autowired
private RestTestClient restTestClient;
@Test
void shouldReturnUserById() {
restTestClient.get()
.uri("/api/users/{id}", 1)
.exchange()
.expectStatus().isOk()
.expectBody(UserVO.class)
.value(user -> assertThat(user.username()).isEqualTo("admin"));
}
}
十、升级建议
| 场景 | 建议 |
|---|---|
| 新项目 | 可以直接评估使用 4.2 |
| 稳定老项目 | 先做技术调研,不要盲目升级 |
| 使用 RestTemplate 的项目 | 开始规划向 RestClient 迁移 |
| 监控系统复杂 | 升级前重点检查指标名和 MDC 字段 |
| CI 使用 Buildpacks | 可以评估共享缓存方案 |
| 对接 LDAPS | 4.2 的 SSL Bundle 支持值得关注 |
Spring Boot 4.2 不是一个“只改版本号”的小更新。
它在消息协议、可观测性、安全连接、构建效率和 API 现代化上都有明确进步。尤其值得关注的是 AMQP 1.0、OpenTelemetry 统一配置、LDAP SSL Bundle 和 RestClient 迁移。
对于 Java 后端开发者,4.2 提供了更现代化的基础能力。但升级前,仍然要结合项目成熟度、监控体系和测试覆盖情况综合评估。
关于作者
魏双喜,写代码也写字。这里是他的独处乐园,记录生活里那些被反复想起的事,和把想法一点点做成产品的过程。