文章
问答
冒泡
Spring Boot 4.0.x 新特性!【真香】

Springboot官网版本发布可见,4.0.x版本将于11月20发布初始版本

https://spring.io/projects/spring-boot

在idea里创建Springboot项目,也可以选择4.0.0 SNAPSHOT

一、新版本架构演进

Spring Boot 4.0 预览版最大的改动之一在于其底层已经全面升级到 Spring Framework 7.0。借助 Spring 7.0 所提供的多项平台特性和现代化功能,Spring Boot 4 在性能、可扩展性及云原生支持方面都有明显提升。具体地:

  • 面向 Java 17+:Spring 7.0 底层抛弃了对旧版 JDK 的兼容,仅支持 JDK 17 及以上。
  • 更加模块化的设计:利用 Java 模块化(JPMS)思想,对常用组件进行拆分,减小运行时体积。
  • 全面支持 Jakarta EE 10 规范:Servlet 6.1、JSP 3.1、WebSocket 2.2 等新标准在 Web 应用中成为默认选项。
  • 采用 Spring AOT(Ahead-of-Time)技术:为 GraalVM 原生映像生成做铺垫,进一步缩短启动时间。

以上架构演进为 Spring Boot 4.0 带来了更好的现代化特性与原生镜像支持

二、核心新特性详解

1. 优雅的 API 版本控制

在微服务架构中,保持 REST 接口的向后兼容性常常十分棘手。Spring Boot 4.0 引入了 版本控制参数,允许开发者在 @RequestMapping 注解中指定 version 属性,从而在同一个 Controller 中维护多个版本的接口实现。

import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/api")
public class TestVersionController {

    // v1 接口
    @RequestMapping(value = "/info", version = "1")
    public String getInfoV1() {
        System.out.println("Version 1");
        return "获取信息 v1";
    }

    // v2 接口(可添加更多字段)
    @RequestMapping(value = "/info", version = "2")
    public String getInfoV2() {
        System.out.println("Version 2");
        return "获取信息 v2(包含更多字段)";
    }
}

在启动后,通过请求不同版本参数可分别访问 /api/info?v=1 与 /api/info?v=2(具体客户端传递方式可自定义),从而实现在不修改 URL 的情况下维护多个版本。此功能极大地简化了接口版本管理工作。

2. 方便的 Bean 注入(BeanRegistrar)

Spring Boot 4.0 提供了 BeanRegistrar 合约,允许在运行时以编程方式注册多个 Bean。与以往必须在 @Configuration 类中逐个声明 @Bean 相比,BeanRegistrar 可以一次性批量注册,并且可以根据环境变量或 Profile 做条件判断。

import org.springframework.beans.factory.BeanRegistrar;
import org.springframework.beans.factory.BeanRegistry;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
import org.springframework.core.env.Environment;

@Configuration
@Import(MyBeansRegistrar.class)
public class MyConfiguration {
}

public class MyBeansRegistrar implements BeanRegistrar {

    @Override
    public void register(BeanRegistry registry, Environment env) {
        // 无条件注册 Studnet Bean
        registry.registerBean("studnet", Studnet.class);

        // 仅在 dev 环境下注册 Article Bean,并通过 supplier 指定构造逻辑
        if (env.acceptsProfiles("dev")) {
            registry.registerBean(Article.class, spec -> 
                spec.supplier(ctx -> new Article("article-001"))
            );
        }
    }
}

@Data
class Studnet {
    private String name;
}

@Data
class Article {
    private String id;
}

上述示例中,通过 @Import(MyBeansRegistrar.class) 将自定义注册器加载到 Spring 容器中。register() 方法内可根据当前环境(Environment)做条件判断,并通过 BeanRegistry 注册 Bean。该机制使得动态注入、Profile 隔离等场景更为简洁

3. Null 安全改进(JSPECIFY 注解)

在大型项目中,空指针异常(NullPointerException)是最常见的隐患之一。Spring Boot 4.0 利用 JSPECIFY 注解(@NonNull、@Nullable)在方法签名中显式声明参数和返回值的可空性,并借助 IDE(如 IntelliJ IDEA)提供编译时或实时提示,从而在编写代码阶段就能避免空指针问题。

import org.jspecify.annotations.NonNull;
import org.jspecify.annotations.Nullable;

public class Person {
    private String name;

    // 参数不可为空
    public void setName(@NonNull String name) {
        this.name = name;
    }

    // 返回值可为空
    @Nullable
    public String getName() {
        return this.name;
    }
}

在上述代码中,若调用方传入 setName(null),IDE 会实时给出警告;若强制编译通过,运行时也可通过字节码增强或 AOT 步骤进行校验。通过在代码级别引入 null 安全机制,可以大幅度降低运行期 NPE 风险。

4. HTTP 代理轻松创建(@ImportHttpServices)

在微服务架构中,通常需要使用 HTTP 客户端调用其他微服务或第三方接口。Spring Boot 4.0 引入了 @ImportHttpServices 注解,结合逻辑组(group)与多个服务接口类型(types),即可自动生成 HTTP 代理客户端,简化了大量模板代码。eg:

import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
import org.springframework.web.bind.annotation.GetMapping;

public interface FreeWeather {
    @GetMapping("/free/weather/today")
    String getTodayWeather(@RequestParam("city") String city);
}

public interface CommercialWeather {
    @GetMapping("/paid/weather/today")
    String getTodayWeatherPaid(@RequestParam("city") String city);
}

@Configuration(proxyBeanMethods = false)
@ImportHttpServices(
    group = "weather",
    types = { FreeWeather.class, CommercialWeather.class }
)
public class HttpServicesConfiguration extends AbstractHttpServiceRegistrar {
    @Bean
    public RestClientHttpServiceGroupConfigurer groupConfigurer() {
        // 通过回调可对所有分组做统一配置,如超时时间、日志拦截等
        return groups -> groups.filterByName("weather");
    }
}

@Service
public class WeatherService {
    private final FreeWeather freeWeatherClient;
    private final CommercialWeather commercialWeatherClient;

    public WeatherService(FreeWeather freeWeatherClient,
                          CommercialWeather commercialWeatherClient) {
        this.freeWeatherClient = freeWeatherClient;
        this.commercialWeatherClient = commercialWeatherClient;
    }

    public void printWeather(String city) {
        System.out.println("免费版天气:" + freeWeatherClient.getTodayWeather(city));
        System.out.println("付费版天气:" + commercialWeatherClient.getTodayWeatherPaid(city));
    }
}

通过上述方式,Spring 容器会基于接口注解生成 HTTP 客户端实现,并可利用 RestClientHttpServiceGroupConfigurer 做分组级别的统一配置。极大简化了 Feign、RestTemplate 等传统方案的手动配置工作

5. 其他七大变更

在上述四项核心特性之外,Spring Boot 4.0 还带来了以下 7 项显著升级:

  1. SPEL 表达式升级
    1. 新增对 空安全操作符(?.)与 Elvis 运算符(?:)的支持,eg:
      //当 pop3.port 未定义时,默认注入 25
      @Value("#{systemProperties['pop3.port'] ?: 25}")
      private int pop3Port;
  2. GraalVM 原生应用支持(Spring AOT)
    1. Spring Boot 4.0 搭配 Spring AOT 插件,可将应用编译为 GraalVM 原生镜像,启动时间缩短至数十毫秒级别,适合 Serverless、容器化无痕部署场景。具体步骤:
      1. 在 pom.xml 中引入 spring-boot-starter 与 spring-aot-maven-plugin;
      2. 执行 mvn spring-boot:build-image 或 mvn spring-boot:build-native-image
  3. 支持 Jackson 3.x
    1. 底层舍弃对 Jackson 2.x 的依赖,全面升级到 Jackson 3.x。所有数据绑定、序列化、反序列化相关的自动配置均默认使用 Jackson 3,若项目中仍使用 Jackson 2,可自行排除并配置依赖,但官方强烈建议尽早切换
  4. Servlet 6.1 与 WebSocket 2.2 版本升级
    1. Spring Boot 4.0 内置 Servlet 6.1 与 WebSocket 2.2,在容器层面要求部署在 Tomcat 11+、Jetty 12.1+ 或其他兼容 Jakarta EE 10 的服务器上
  5. HttpHeaders 优化
    1. 引入新的 HttpHeaders API,内部使用 CharSequence 池化与常量重构,大幅度提升 Header 处理性能;
    2. 在常见场景下,如频繁设置自定义 Header、不使用 RestTemplate 时,可直接使用 HttpHeaders.of(...) 等静态工厂方法,无需手动创建大量 new HttpHeaders() 对象,降低 GC 频率
  6. Actuator 端点增强
    1. 新增对 Micrometer 1.11 的深度集成,支持 OTLP、Prometheus、Elastic 等监控系统的自动化配置
    2. Health 指标自动感知更多系统组件(如 Kubernetes Readiness/Liveness、PostgreSQL 读写分离状态等)
    3. 动态属性刷新(/actuator/refresh)可针对单个 Bean 进行配置更新,而不影响其他服务
  7. 测试优化与 Mock 支持
    1. @SpringBootTest 默认启用 JUnit 5.9 及以上版本,且对 Mockito 5.x 做了兼容
    2. 新增 @DynamicPropertySource 在 Spring Boot 上下文中动态注入属性的能力,使得在集成测试中更灵活地模拟不同环境配置
    3. 对 Spring MVC、WebFlux 的 Mock 支持进一步加强,可通过 MockMvc、WebTestClient 实现对带版本控制、HttpServicesProxy 等新功能的端到端测试

Spring Boot 4.0 预览版基于 Spring Framework 7.0 做了诸多现代化改造与性能优化,有兴趣的可以上手体验这些现代化的新特性。

Springboot 4.0

关于作者

Miraclewcg
上善若水
获得点赞
文章被阅读