Spring Boot 4.0官宣: 弃用 Undertow:Tomcat笑麻了

4,416 阅读3分钟

Spring Boot 4.0.0 M2 里程碑版本发布后,社区反响热烈,其中最引人关注的变动之一就是 正式移除对 Undertow 的内嵌支持。本文将深入解析这一决策背后的技术原因、对现有项目的影响,以及开发者应如何平稳过渡。

在这里插入图片描述


一、Undertow 被弃用:不是“抛弃”,而是“规范对齐”

在 Spring Boot 3.x 及更早版本中,开发者可以选择三种内嵌 Web 容器:

  • Tomcat(默认)
  • Jetty
  • Undertow

其中,Undertow 因其 低内存占用、高并发吞吐能力、天然支持持久连接 等优势,被不少高并发场景下的企业项目采用。

然而,在 Spring Boot 4.0 中,官方彻底移除了对 Undertow 的支持。这不是 Spring 团队的主观决策,而是技术生态演进的必然结果:

Undertow 尚未适配 Servlet 6.1 规范,而 Spring Boot 4.0 基于 Spring Framework 7,强制依赖 Servlet 6.1

由于 Red Hat(Undertow 的维护方)对该项目的投入有限,导致 Undertow 无法及时跟进新规范。Spring Boot 无法在缺乏底层支持的情况下继续维护兼容层,因此只能做出移除决定。

关键结论:只要 Undertow 未来支持 Servlet 6.1,Spring Boot 仍有可能恢复对其支持。


二、对现有项目的影响

如果你的项目当前使用了如下配置:

server:
  servlet:
    context-path: /api
  undertow:
    io-threads: 4
    worker-threads: 20
    buffer-size: 1024

或依赖:

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-undertow</artifactId>
</dependency>

那么在升级到 Spring Boot 4.0 后,项目将无法启动,并抛出类似错误:

Caused by: java.lang.IllegalStateException: 
  Unable to find Undertow-based WebServer implementation.

风险点总结:

风险项说明
启动失败缺少 Undertow 实现类
配置失效server.undertow.* 配置被忽略
性能回退切换容器后需重新压测调优

三、迁移方案:如何平滑过渡?

方案 1:切换回 Tomcat(推荐)

Tomcat 是 Spring Boot 默认容器,生态成熟、文档丰富,且在 Spring Boot 4 中已全面适配 Servlet 6.1。

步骤:

  1. 移除 Undertow 依赖:

    <!-- 删除以下依赖 -->
    <!--
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-undertow</artifactId>
    </dependency>
    -->
    
  2. 显式添加 Tomcat(通常无需添加,因 spring-boot-starter-web 已默认包含):

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-tomcat</artifactId>
    </dependency>
    
  3. server.undertow.* 配置转换为 server.tomcat.*(如有必要):

    server:
      tomcat:
        threads:
          max: 200
          min-spare: 10
        max-connections: 8192
    

方案 2:改用 Jetty

Jetty 同样支持 Servlet 6.1,且在某些 I/O 密集型场景下表现优异。

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-jetty</artifactId>
</dependency>

⚠️ 注意:需排除 Tomcat 依赖,避免冲突:

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
    <exclusions>
        <exclusion>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-tomcat</artifactId>
        </exclusion>
    </exclusions>
</dependency>

四、Spring Boot 4.0 其他重要变更(简要)

除了 Undertow 移除,Spring Boot 4 还带来多项重大更新:

类别变更内容
构建工具Gradle 需 ≥ 8.14 或 9.x
可观测性新增 spring-boot-starter-opentelemetry,支持 OTLP 指标与追踪
API 管理内置 API 版本控制(Spring MVC / WebFlux)
HTTP 客户端引入 @HttpServiceClient 简化远程调用
空值安全支持 JSpecify 注解(@Nullable / @NonNull
虚拟线程启用 spring.threads.virtual.enabled=true 可使用 JDK 虚拟线程提升并发

五、结语:拥抱变化,面向未来

Undertow 的退出,标志着 Spring Boot 正在加速向 云原生、可观测性、现代化 Java(JDK 21+) 演进。虽然短期带来迁移成本,但长期看,这是生态健康发展的体现。