Spring Boot 3.5 新特性

Spring Boot 3.5 本月即将发布,带来了诸多值得关注的能力提升。以下是本次更新的关键亮点:

  • • 🚀 任务调度增强:TaskDecorator优化定时任务
  • • 💾 Vibur连接池:高性能数据库连接新选择
  • • 🔒 安全监控升级:SSL证书状态一目了然
  • • ⚙️ 配置管理优化:环境变量、配置处理更灵活
  • • 🔍 链路追踪完善:Trace ID自动写入HTTP响应头
  • • 📊 运维体验提升:Actuator功能全面增强
  • • 🌟 函数式编程支持:提前体验Spring Framework 7新特性

二、新特性详解

1. 任务装饰器:定时任务更强大

Spring Boot 3.5现在会自动将应用上下文中的TaskDecorator Bean应用于所有定时任务调度器。

@Bean
public TaskDecorator myTaskDecorator() {
    return taskDecorator -> {
        // 获取主线程上下文信息
        String userId = UserContext.getCurrentUserId();
        // 返回包装后的任务
        return () -> {
            // 在子线程中设置上下文
            ....
        };
    };
}

无需手动编写大量样板代码,安全上下文和MDC日志信息的传递变得异常简单,尤其适合处理多租户上下文和统一权限。

2. Vibur连接池:性能优化新选择

除了HikariCP、Tomcat、Dbcp2和OracleUcp,Spring Boot 3.5新增了对Vibur DBCP连接池的支持。

spring:
  datasource:
    type: io.vibur.dbcp.ViburDBCPDataSource

Vibur DBCP提供了高级性能监控功能,能够检测慢SQL查询、防止线程饥饿,并支持JDBC语句缓存,适合对数据库性能要求严苛的应用。

3. SSL Bundle指标:安全监控一目了然

Actuator现在提供了SSL证书链的健康状态指标,包括有效、过期、即将过期和尚未生效的分类统计。

management:
  endpoints:
    web:
      exposure:
        include: health,info,ssl
  ssl:
    bundles:
      enabled: true

运维团队可实时监控SSL证书状态,及时发现即将过期的证书,避免因证书过期导致的服务中断。

4. 环境变量配置加载:多环境部署更轻松

Spring Boot 3.5允许从单个环境变量中加载多个配置属性,大大简化了容器化部署。

# 在application.yml中
spring:
  config:
    import: env:MY_CONFIGURATION
# 设置环境变量
MY_CONFIGURATION='
datasource.url=jdbc:mysql://prod-db:3306/myapp
datasource.username=prod_user
datasource.password=prod_password
'

在Docker和Kubernetes环境中,可通过单个环境变量传递多个配置项,避免了为每个配置创建单独环境变量的繁琐操作。

5. Actuator触发Quartz任务:运维更智能

现在可以通过HTTP接口触发Quartz任务,无需等待预设的调度时间。

# 触发指定的Quartz任务
curl -X POST http://localhost:8080/actuator/quartz/jobs/DEFAULT/syncDataJob

运维人员可以通过简单HTTP请求手动触发定时任务,极大提升了紧急情况下的响应速度。

6. HTTP响应头Trace ID:链路追踪无缝集成

与Micrometer Observations和Tracing集成时,可自动将Trace ID写入HTTP响应头。

management:
  observations:
    http:
      server:
        requests:
          write-trace-header: true

在微服务架构中,前端可直接获取Trace ID进行问题报告,大幅提升全链路故障排查效率。

7. 结构化日志栈追踪定制:排查问题一键直达

Spring Boot 3.5允许自定义结构化日志中的堆栈跟踪信息输出。

logging:
  structured:
    json:
      stacktrace:
        max-depth: 20
        packaged-only: true
        include-packages: com.mycompany
        exclude-packages: org.springframework,java.lang

可以只输出业务代码相关的堆栈信息,过滤掉框架代码,让日志更加清晰易读,问题定位更精准。

8. WebMvc函数路由信息:API管理更全面

Mappings端点现在包含了关于WebMvc.fn函数式路由的详细信息。

@Bean
public RouterFunction<ServerResponse> routerFunction() {
    return route()
        .GET("/api/users", this::getAllUsers)
        .POST("/api/users", this::createUser)
        .build();
}

9. 服务连接SSL支持:数据传输更安全

为多种服务连接添加了客户端SSL支持,包括Cassandra、Couchbase、Elasticsearch、Kafka、MongoDB、RabbitMQ和Redis。

spring:
  data:
    mongodb:
      ssl:
        enabled:true
        bundle:mongodb-bundle
ssl:
    bundles:
      mongodb-bundle:
        keystore:
          location:classpath:mongodb-keystore.p12
          password:secret
          type: PKCS12

简化与后端服务的安全通信配置,保障数据传输安全,满足合规要求。

10. OpenTelemetry改进:分布式追踪更规范

支持通过配置属性和环境变量设置OpenTelemetry资源属性,并添加对service.namespace的支持。

management:
  tracing:
    opentelemetry:
      resource:
        attributes:
          service.name: my-service
          service.namespace: my-group
      export:
        otlp:
          endpoint: http://tempo:4317

11. Spring Batch增强:批处理更灵活

可自定义JobParametersConverter,并控制事务状态验证。

@Bean
public JobParametersConverter customJobParametersConverter() {
    return new MyCustomJobParametersConverter();
}
spring:
  batch:
    jdbc:
      validate-transaction-state: false

实战价值:提供更灵活的批处理任务参数处理机制,适应复杂的批处理业务场景。

12. OAuth 2.0 JWT Profile:认证更标准

Spring Security 6.5.0引入了对RFC 9068标准的支持,规范化OAuth 2.0访问令牌的JWT格式。

@Bean
public JwtEncoder jwtEncoder() {
    returnnewNimbusJwtEncoder(jwkSource());
}

@Bean
public OAuth2TokenCustomizer<JwtEncodingContext> jwtCustomizer() {
    return context -> {
        JwtClaimsSet.Builderclaims= context.getClaims();
        claims.claim("client_id", context.getRegisteredClient().getClientId());
        // 符合RFC 9068的其他必要声明
    };
}

提高OAuth 2.0访问令牌的互操作性和安全性,更容易与第三方系统集成。

13. 函数式Bean注册:提前体验Spring 7新特性

通过BeanRegistrar接口支持函数式Bean注册,预览Spring Framework 7的新特性。

public classMyBeanRegistrarimplementsBeanRegistrar {
    @Override
    publicvoidregisterBeans(BeanRegistry registry, Environment environment) {
        // 基于条件动态注册Bean
        if (environment.containsProperty("feature.enabled")) {
            registry.registerBean(MyService.class, MyService::new);
        }
    }
}

@Import(MyBeanRegistrar.class)
@Configuration
publicclassAppConfig {
    // ...
}

需要在运行时根据特定条件或逻辑动态注册Bean的高级场景,提供了比@Conditional注解更灵活的选择。

来源:https://mp.weixin.qq.com/s/nTQag7pa1yTCFqbc4C4mwQ

请登录后发表评论

    没有回复内容