前言
starter可以認(rèn)為是一種服務(wù)歼指,某個功能開發(fā)者不需要關(guān)注各種依賴庫的處理,不需要具體的配置信息鸟妙。由Springboot自定注入需要的bean扬绪。比如spring-boot-starter-jdbc這個starter的存在。我們直接使用@Autowired
引入DataSource的bean就可以赛蔫,Spring Boot會自動創(chuàng)建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/下創(chuàng)建spring.factories文件
org.springframework.boot.autoconfigure.EnableAutoConfiguration=\
com.dankun.autoconfig.DankunAutoConfigure
使用
修改application.yml配置文件呵恢,添加如下內(nèi)容:
example.service:
enabled: true
prefix: ppp
suffix: sss
測試類
@SpringBootTest
public class ApplicationTests {
private DankunService dankunService;
public void testStarter() {
System.out.println(dankunService.wrap("hello"));
}
}