前言
starter可以认为是一种服务,某个功能开发者不需要关注各种依赖库的处理,不需要具体的配置信息。由Springboot自定注入需要的bean。比如spring-boot-starter-jdbc这个starter的存在。我们直接使用@Autowired
引入DataSource的bean就可以,Spring Boot会自动创建DataSource的实例。
实例
添加maven依赖
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-autoconfigure</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-configuration-processor</artifactId>
<optional>true</optional>
</dependency>
</dependencies>
编写需要定义的Bean
public class DankunService {
private String prefix;
private String suffix;
public DankunService(String prefix, String suffix) {
this.prefix = prefix;
this.suffix = suffix;
}
public String wrap(String word) {
return prefix + word + suffix;
}
}
编写属性类
@ConfigurationProperties("dankun.service")
public class DankunServiceProperties {
private String prefix;
private String suffix;
public String getPrefix() {
return prefix;
}
public void setPrefix(String prefix) {
this.prefix = prefix;
}
public String getSuffix() {
return suffix;
}
public void setSuffix(String suffix) {
this.suffix = suffix;
}
}
编写自动配置类
@Configuration
@ConditionalOnClass(DankunService.class)
@EnableConfigurationProperties(DankunServiceProperties.class)
public class DankunAutoConfigure {
private final DankunServiceProperties properties;
@Autowired
public DankunAutoConfigure(DankunServiceProperties properties) {
this.properties = properties;
}
@Bean
@ConditionalOnMissingBean
@ConditionalOnProperty(prefix = "dankun.service", value = "enabled",havingValue = "true")
DankunService dankunService() {
return new DankunService(properties.getPrefix(), properties.getSuffix());
}
}
添加spring.factories
最后一步,在resources/META-INF/下创建spring.factories文件
org.springframework.boot.autoconfigure.EnableAutoConfiguration=\
com.dankun.autoconfig.DankunAutoConfigure
使用
修改application.yml配置文件,添加如下内容:
example.service:
enabled: true
prefix: ppp
suffix: sss
测试类
@SpringBootTest
public class ApplicationTests {
private DankunService dankunService;
public void testStarter() {
System.out.println(dankunService.wrap("hello"));
}
}
网友评论