spring boot 自定义 starter 的核心是自动装配机制,需遵循命名规范(如 xxx-spring-boot-starter)、模块拆分(starter + autoconfigure)、使用 meta-inf/spring/org.springframework.boot.autoconfigure.autoconfiguration.imports 声明配置类、通过 @configurationproperties 支持可配参数,并用 @conditionalonclass 和 @conditionalonmissingbean 等条件注解确保装配健壮性。

编写 Spring Boot 自定义 Starter,核心是让外部项目“引入即用”——不写配置、不手动注册 Bean、不扫包,只要加依赖,功能就自动生效。这背后靠的是自动装配机制,不是魔法,而是有明确结构和约定的一套工程实践。
命名与项目结构要规范
项目名必须遵循 xxx-spring-boot-starter 格式(如 mycache-spring-boot-starter),这是 Spring Boot 官方约定,便于识别和管理。结构上建议拆为两个模块:
- starter 模块:纯 pom 工程,只声明依赖,不写任何 Java 代码,作用是统一版本、传递依赖
-
autoconfigure 模块:含自动配置逻辑的核心模块,包含
@Configuration类、@ConfigurationProperties类、条件注解、Bean 定义等
starter 模块需依赖 autoconfigure 模块;最终使用者只引入 starter 模块即可。
自动配置类必须被 Spring Boot 扫描到
Spring Boot 不会自动扫描 jar 包里的配置类,必须通过标准路径显式声明。在 autoconfigure 模块的 src/main/resources/META-INF/spring/ 下创建文件:
org.springframework.boot.autoconfigure.AutoConfiguration.imports
文件内容为一行或多行全限定类名,例如:
com.example.mycache.autoconfigure.MyCacheAutoConfiguration
注意:Spring Boot 2.7+ 已弃用旧版 spring.factories,必须使用此新路径;否则配置类不会被加载。
在 Java 中初始化和管理阿里云 SDK客户端。包括单例模式、线程安全、endpoint 与 region 配置、VPC 终端节点、同步与异步等。
支持用户可配参数,用 ConfigurationProperties
如果 Starter 允许外部调整行为(比如开关、超时、地址),就定义属性类:
@ConfigurationProperties(prefix = "mycache")<br>public class MyCacheProperties {<br> private boolean enabled = true;<br> private int timeout = 3000;<br> // getter/setter<br>}
并在自动配置类上用 @EnableConfigurationProperties(MyCacheProperties.class) 启用绑定。这样用户只需在 application.yml 写:
mycache:<br> enabled: true<br> timeout: 5000
用条件注解控制装配时机
避免无脑创建 Bean,要用 @ConditionalOnClass、@ConditionalOnMissingBean 等保证健壮性。典型写法:
@Configuration<br>@ConditionalOnClass(CacheManager.class)<br>@EnableConfigurationProperties(MyCacheProperties.class)<br>public class MyCacheAutoConfiguration {<br><br> @Bean<br> @ConditionalOnMissingBean<br> public CacheService cacheService(MyCacheProperties properties) {<br> return new DefaultCacheService(properties);<br> }<br>}
这样既防止冲突,又兼容已有配置,也符合 Spring Boot “约定大于配置”的设计哲学。










