1. 自定义 starter
通常来说,启动器只用来做依赖导入,没有任何代码,所以需要专门来写一个自动配置模块
如果是 Spring Boot 内部提供的组件,一般叫 spring-boot-starter-xxx
,如果是第三方组件集成 Spring Boot,一般是叫 xxx-spring-boot-starter
,如 mybatis-spring-boot-starter
2. 环境搭建
代码已经上传至 https://github.com/masteryourself-tutorial/tutorial-spring ,详见
tutorial-spring-boot-core/tutorial-spring-boot-starter
工程
2.1 sample-spring-boot-starter-autoconfigure
自动配置模块
2.1.1 配置文件
1. META-INF/spring.factories
org.springframework.boot.autoconfigure.EnableAutoConfiguration=\
pers.masteryourself.tutorial.spring.boot.starter.sample.SampleAutoConfiguration
2.1.2 核心代码
1. SampleAutoConfiguration
@Configuration
@ConditionalOnClass(SampleService.class)
@EnableConfigurationProperties(SampleProperties.class)
public class SampleAutoConfiguration {
private SampleProperties properties;
public SampleAutoConfiguration(SampleProperties properties) {
this.properties = properties;
}
@Bean
public SampleService sampleService() {
return new SampleService(properties);
}
}
2. SampleService
public class SampleService {
private SampleProperties properties;
public SampleService(SampleProperties properties) {
this.properties = properties;
}
public String say(String str) {
return properties.getPrefix() + " [" + str + "] " + properties.getSuffix();
}
}
3. SampleProperties
@Data
@ConfigurationProperties(prefix = "sample")
public class SampleProperties {
private String prefix;
private String suffix;
}
2.2 sample-spring-boot-starter
自定义启动器,无任何代码,只做依赖
2.2.1 配置文件
1. pom.xml
<dependencies>
<dependency>
<groupId>pers.masteryourself.tutorial.spring</groupId>
<artifactId>sample-spring-boot-starter-autoconfigure</artifactId>
</dependency>
</dependencies>
2.3 sample-spring-boot-starter-test
测试工程
2.3.1 配置文件
1. application.properties
sample.prefix=author:masteryourself
sample.suffix=created
2.3.2 核心代码
1. SampleServiceTestApplication
@SpringBootApplication
public class SampleServiceTestApplication implements CommandLineRunner {
@Autowired
private SampleService sampleService;
public static void main(String[] args) {
SpringApplication.run(SampleServiceTestApplication.class, args);
}
@Override
public void run(String... args) throws Exception {
System.out.println(sampleService.say("hello"));
}
}