Spring应用与开发 工程进阶 Spring Boot 3.4+

Spring Boot 3.4+ 自动装配原理剖析与自定义企业级 Starter 实战

从 AutoConfiguration.imports 机制到 @ConditionalOnMissingBean 优雅设计可插拔基础组件

更新日期:2026-11-25 · 预计阅读:9 分钟 · 阅读量:2,473
核心提要:详解 Spring Boot 3.x 废弃 spring.factories 后的全新自动装配加载流程,手把手示范如何封装一个支持属性校验、默认可覆盖的通用企业级防重提交 Starter。

一、Spring Boot 3.x 自动装配核心变化

相比 Spring Boot 2.x 扫描 META-INF/spring.factories,Spring Boot 3.x 起改用专属注册文件:

META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports

文件内每行一个自动配置类的全限定名,搭配类上的 @AutoConfiguration(底层设置 proxyBeanMethods = false 减少 CGLIB 代理开销)以及各类 @ConditionalOnClass、@ConditionalOnProperty、@ConditionalOnMissingBean 条件注解,实现“引入依赖即生效、业务自定义即让位”的优雅体验。

二、自定义企业级 Starter 四步标准规范

  1. 命名规范:官方使用 spring-boot-starter-xxx,企业内部统一使用 xxx-spring-boot-starter(例如 idempotent-spring-boot-starter)。
  2. 强类型配置绑定:使用 @ConfigurationProperties(prefix = "acme.idempotent") + Jakarta Validation 注解在启动期校验必填项。
  3. 编写自动配置类:为所有默认 Bean 添加 @ConditionalOnMissingBean,方便业务方定制替换。
  4. 注册 imports 文件:将自动配置类写入 AutoConfiguration.imports。
@AutoConfiguration
@EnableConfigurationProperties(IdempotentProperties.class)
@ConditionalOnProperty(prefix = "acme.idempotent", name = "enabled", havingValue = "true", matchIfMissing = true)
public class IdempotentAutoConfiguration {

    @Bean
    @ConditionalOnMissingBean
    public IdempotentKeyResolver defaultKeyResolver() {
        return new DefaultSpelKeyResolver();
    }

    @Bean
    @ConditionalOnMissingBean
    public IdempotentAspect idempotentAspect(IdempotentKeyResolver resolver, IdempotentProperties props) {
        return new IdempotentAspect(resolver, props);
    }
}