当前位置: 首页 > 图灵资讯 > 技术篇> Java 中怎么在 Spring Boot 中编写自定义 Starter 封装通用业务组件

Java 中怎么在 Spring Boot 中编写自定义 Starter 封装通用业务组件

来源:图灵教育
时间:2026-09-07 10:39:47
Spring Boot 自定义 Starter 的核心是遵循“约定优于配置”原则,通过 autoconfigure 模块(含自动配置类、属性绑定、条件注解)和 starter 模块(纯 pom,声明依赖)实现开箱即用;以短信组件为例,需定义 SmsProperties、SmsAutoConfiguration,并在 META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports 中注册配置类,最后通过集成测试验证并发布使用。

在 Spring Boot 中编写自定义 Starter,核心是把通用业务逻辑封装成可自动装配、开箱即用的模块,让其他项目只需引入依赖 + 简单配置就能使用。关键不在“写代码”,而在“约定优于配置”——遵循 Spring Boot 的自动装配机制。

理解 Starter 的组成结构

一个规范的 Starter 通常包含两个模块(也可合为一个):

  • xxx-spring-boot-autoconfigure:含自动配置类(@Configuration)、条件注解(@ConditionalOnClass、@ConditionalOnMissingBean等)、属性绑定类(@ConfigurationProperties)和核心 Bean 定义;
  • xxx-spring-boot-starter:纯 pom 工程,只负责引入 autoconfigure 模块 + 其他必要依赖(如 slf4j、commons-lang3),不写任何 Java 代码。

这样设计是为了分离“配置逻辑”和“依赖声明”,方便使用者按需选择是否启用某些功能。

编写自动配置模块(autoconfigure)

以封装一个通用的「短信发送组件」为例:

立即学习

“Java免费学习笔记(深入)”;

JAVA JDK 22.0.2

下载 JAVA JDK 22.0.2 历史版本,并查看对应 Windows、macOS、Linux 官方安装入口。

下载

  • 定义配置属性类:SmsProperties,用 @ConfigurationProperties("sms") 绑定 application.yml 中的 sms.provider、sms.timeout 等字段;
  • 编写自动配置类:SmsAutoConfiguration,加上 @EnableConfigurationProperties(SmsProperties.class) 和 @ConditionalOnProperty(prefix = "sms", name = "enabled", havingValue = "true", matchIfMissing = true) 控制是否生效;
  • 在该配置类中定义 @Bean 方法,例如返回 SmsService 实例,并根据 sms.provider 值决定注入 AliyunSmsService 还是 TencentSmsService;
  • 确保类路径下有 META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports 文件(Spring Boot 2.7+ 推荐方式),内容为你的配置类全限定名,如:com.example.sms.autoconfigure.SmsAutoConfiguration
编写 Starter 模块(starter)

这是一个空的 Maven 模块,pom.xml 只做一件事:声明依赖。

  • 打包类型设为 pom;
  • 依赖中引入自己的 autoconfigure 模块(compile 范围);
  • 把真正运行时需要的第三方库(如 http client、json 处理器)也声明进来,避免使用者重复引;
  • 不要添加 spring-boot-starter 或 spring-boot-starter-web 等基础 starter——除非你明确要求宿主应用必须是 Web 环境。
测试与使用

本地测试建议用 spring-boot-starter-test 写集成测试:

  • 新建测试模块或在 autoconfigure 模块中加 @SpringBootTest 类;
  • 用 @ImportAutoConfiguration 导入你的配置类,或直接 @ContextConfiguration 加载;
  • 验证 SmsService 是否成功注入、属性是否正确绑定、条件注解是否按预期生效。

发布到私有 Maven 仓库后,其他项目只需在 pom.xml 中添加 starter 依赖,再在 application.yml 配置 sms.enabled=true 和相关参数,即可直接 @Autowired SmsService 使用。