spring boot自定义starter必须遵循starter-autoconfigure模块分离结构,通过meta-inf/spring/org.springframework.boot.autoconfigure.autoconfiguration.imports注册条件化配置类,并绑定@configurationproperties实现外部可配,从而达成“引入即用”。

要在Spring Boot项目中统一管理中间件依赖、避免手动配置重复出错,并让团队新成员三步接入Redis或自定义服务,必须掌握Starter的依赖聚合机制与自动装配原理。
创建符合规范的Starter模块结构
新建Maven模块,命名为mycompany-redis-spring-boot-starter——【命名必须以-spring-boot-starter结尾,否则Spring Boot不会识别为Starter】。
在该模块的pom.xml中仅声明对autoconfigure模块的依赖,不引入任何业务代码或第三方库。
另建一个同名但后缀为-spring-boot-autoconfigure的模块(如mycompany-redis-spring-boot-autoconfigure),所有配置类、属性类、Bean定义都放在这里。
这种拆分不是可选建议,而是强制要求:starter模块只做依赖传递,autoconfigure模块承载全部自动装配逻辑,否则无法实现条件化加载与版本隔离。
编写可外部配置的属性绑定类
在autoconfigure模块中创建RedisClientProperties类:
添加@ConfigurationProperties(prefix = "mycompany.redis")注解,并声明host、port、timeout等字段;每个字段必须设默认值,比如private int port = 6379;。
加上@Component和@Validated,确保该类能被Spring容器扫描并校验。
这一步不做,后续yml里的mycompany.redis.host就无法注入到Bean中,整个配置体系会失效。
定义条件化自动配置类
方法一:使用@ConditionalOnClass控制生效时机
创建RedisClientAutoConfiguration类,标注@Configuration和@EnableConfigurationProperties(RedisClientProperties.class)。
在类中定义@Bean方法返回RedisClient实例,方法参数直接接收RedisClientProperties对象——Spring会自动注入已绑定的配置。
在该@Bean方法上添加@ConditionalOnClass(RedisClient.class),确保只有项目里真有这个类时才创建Bean。
方法二:用@ConditionalOnProperty开关控制启用
在同一个@Bean方法上追加@ConditionalOnProperty(name = "mycompany.redis.enabled", havingValue = "true", matchIfMissing = true)。
【matchIfMissing = true表示配置项未显式声明时,默认启用,避免因漏配导致功能静默失效】。
注册自动配置类到Spring Boot扫描链
第一步:在autoconfigure模块的src/main/resources/META-INF/下创建spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports文件(注意路径和文件名完全匹配)。
第二步:在该文件中逐行写入自动配置类的全限定名,例如:
com.mycompany.starter.redis.autoconfigure.RedisClientAutoConfiguration
第三步:确认该文件编码为UTF-8且无BOM头,否则Spring Boot启动时读取失败,自动配置类不会被加载。
第四步:执行mvn clean install将autoconfigure模块安装到本地仓库,再让starter模块依赖它。
在业务项目中引入并验证Starter
在目标Spring Boot项目的pom.xml中添加starter依赖:
<dependency><groupid>com.mycompany</groupid><artifactid>mycompany-redis-spring-boot-starter</artifactid><version>1.0.0</version></dependency>
在application.yml中写入:
mycompany:redis:host: 127.0.0.1
启动应用,观察控制台是否打印Redis连接初始化日志;若无报错且@Autowired RedisClient可成功注入,则Starter已生效。











