目录
[一、创建 Starter 项目结构](#一、创建 Starter 项目结构)
[六、使用 Maven 打包项目](#六、使用 Maven 打包项目)
[七、在其他 Spring Boot 项目中使用 Starter](#七、在其他 Spring Boot 项目中使用 Starter)
[1. 引入 Starter 依赖](#1. 引入 Starter 依赖)
[2. 直接注入使用](#2. 直接注入使用)
一、创建 Starter 项目结构
Spring Boot 官方建议第三方 Starter 的命名格式为:xxx-spring-boot-starter
因此我们创建一个名为 my-spring-boot-starter的 Maven 项目,并包含两个模块:
perl
my-spring-boot-starter
├── my-spring-boot-autoconfigure
└── my-spring-boot-starter
模块职责说明
- autoconfigure 模块
- 存放自动配置逻辑
- 包含自动配置类、配置属性类、业务类
- starter 模块
- 只包含依赖声明
- 对外作为 Starter 使用
二、创建自动配置类
在 my-spring-boot-autoconfigure 模块中创建自动配置类,一般放在 autoconfigure 包下。
java
@Configuration
@EnableConfigurationProperties(MyProperties.class)
@ConditionalOnClass(MyService.class)
@ConditionalOnMissingBean(MyService.class)
public class MyAutoConfiguration {
@Bean
public MyService myService(MyProperties properties) {
return new MyService(properties.getPrefix());
}
}
说明
- @Configuration:声明这是一个配置类
- @EnableConfigurationProperties:启用配置属性绑定
- @ConditionalOnClass:类存在时才生效
- @ConditionalOnMissingBean:用户未自定义 Bean 时才创建
三、创建配置属性类
配置属性类用于读取 application.yml 或 application.properties 中的配置。
java
@ConfigurationProperties(prefix = "my.starter")
public class MyProperties {
private String prefix = "Hello";
public String getPrefix() {
return prefix;
}
public void setPrefix(String prefix) {
this.prefix = prefix;
}
}
对应配置文件示例:
perl
my:
starter:
prefix: Hi
四、创建业务服务类
创建一个简单的服务类,用于提供具体业务逻辑。
java
public class MyService {
private final String prefix;
public MyService(String prefix) {
this.prefix = prefix;
}
public String sayHello(String name) {
return prefix + " " + name;
}
}
该类不需要任何 Spring 注解,由自动配置类负责注册。
五、注册自动配置类
在 my-spring-boot-autoconfigure 模块的:
css
src/main/resources/META-INF
目录下创建文件:spring.factories
内容如下:
XML
org.springframework.boot.autoconfigure.EnableAutoConfiguration=\
com.example.autoconfig.MyAutoConfiguration
该文件用于告诉 Spring Boot:在启动时加载我们自定义的自动配置类。
六、使用 Maven 打包项目
在父工程目录执行:
bash
mvn clean install
打包完成后:
- autoconfigure 模块作为普通依赖
- starter 模块作为最终对外使用的 Starter
七、在其他 Spring Boot 项目中使用 Starter
1. 引入 Starter 依赖
XML
<dependency>
<groupId>com.example</groupId>
<artifactId>my-spring-boot-starter</artifactId>
<version>1.0.0</version>
</dependency>
2. 直接注入使用
java
@RestController
public class TestController {
@Autowired
private MyService myService;
@GetMapping("/hello")
public String hello(String name) {
return myService.sayHello(name);
}
}
无需任何额外配置,即可正常使用。
通过以上步骤,我们完成了一个自定义 Spring Boot Starter:
- Starter 模块负责依赖聚合
- AutoConfigure 模块负责自动装配
- 利用条件注解保证安全、可扩展
自定义 Spring Boot Starter 的核心,就是通过自动配置机制,把通用功能封装成"引入即用"的模块。