自定义 Starter:自动配置编写与 spring.factories/AutoConfiguration.imports

团队内常把通用能力(短信、对象存储、公共安全)做成"开箱即用"的 starter:别人引入一个依赖,无需写 @Configuration 就能拿到 Bean。其核心是 Spring Boot 的自动配置机制。本文件以 Boot 3.x 为准:自动配置的注册文件是 AutoConfiguration.importsspring.factories 方式在 Boot 3.0 已被移除。

Starter 的结构:聚合 + 自动配置

一个 starter 通常拆两个模块(也可合并):

  • xxx-spring-boot-starter:空壳 pom,只依赖下面的 autoconfigure 模块;
  • xxx-spring-boot-autoconfigure:真正的自动配置类与属性类。

编写自动配置类

以"问候服务 hello"为例:

@AutoConfiguration                          // 标记这是自动配置类
@ConditionalOnClass(HelloService.class)     // 依赖类存在才生效
@EnableConfigurationProperties(HelloProperties.class)
public class HelloAutoConfiguration {

    @Bean
    @ConditionalOnMissingBean               // 用户已自定义则不再重复创建
    public HelloService helloService(HelloProperties props) {
        return new HelloService(props.getPrefix());
    }
}

可配置项用 @ConfigurationProperties 承载:

@ConfigurationProperties(prefix = "hello")   // application.yml 里 hello.prefix=...
public class HelloProperties {
    private String prefix = "你好";          // 默认值
    // getter/setter 省略
}

注册自动配置类

在 autoconfigure 模块的 resources 下新建文件,一行一个全限定类名:

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

文件内容示例:

com.example.hello.HelloAutoConfiguration

该文件自 Boot 2.7 引入并取代 spring.factories 里的 org.springframework.boot.autoconfigure.EnableAutoConfiguration 键;Boot 3.0 起 spring.factories 注册自动配置的方式不再生效,老工程升级必须迁移。

常用条件注解

  • @ConditionalOnClass / @ConditionalOnMissingClass:按依赖类判定;
  • @ConditionalOnBean / @ConditionalOnMissingBean:按 Bean 判定(防重复注册);
  • @ConditionalOnProperty:按配置项(如 hello.enabled=true)开关;
  • @ConditionalOnWebApplication:区分 Web 应用类型;
  • 排序用 @AutoConfigureBefore / @AutoConfigureAfter

使用与排查

使用方只需引入 starter 依赖,配置 hello.prefix 即可注入 HelloService。调试技巧:

  • spring-boot-autoconfigure-processor(optional 依赖)生成配置元数据,IDE 里会有属性提示;
  • 启动日志切 debug 后查看 "Positive matches / Negative matches",能定位自动配置为什么没生效。

小结:自动配置 = @AutoConfiguration + 条件注解 + 属性类,靠 META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports 注册;Boot 3 不再读 spring.factories。

笔记加载中…