springboot中的starter及自定義方法詳解
1:官方提供的starter
在spring-boot-autocongure包中定義了官方提供的一百多個starter,如下:

2:框架是如何定義starter的?
因為springboot的普及度逐步提高,一些沒有被官方實現(xiàn)提供為starter的框架,也會自己實現(xiàn)一個starter供用戶使用,這里以shardingsphere ,clone之后使用操作git checkout -b 5.0.0-alpha-local 5.0.0-alpha創(chuàng)建分支,然后在如下目錄查看starter配置:
$ pwd /d/test/sharding-sphere/shardingsphere-jdbc/shardingsphere-jdbc-spring/shardingsphere-jdbc-core-spring/shardingsphere-jdbc-core-spring-boot-starter
截圖如下:

spring.provider內(nèi)容如下:
provides: shardingsphere-jdbc-spring-boot-starter
additional-spring-configuration-metadata.json內(nèi)容如下:
{
"groups": [
{
"name": "spring.shardingsphere.datasource",
"type": "org.apache.shardingsphere.spring.boot.SpringBootConfiguration"
},
...
}
其中比較重要的是spring.factories和自動配置類SpringBootConfiguration,spring.factories如下:
org.springframework.boot.autoconfigure.EnableAutoConfiguration=\ org.apache.shardingsphere.spring.boot.SpringBootConfiguration
其中只定義了自動配置類,自動配置類如下:
@Configuration // 代表是一個Java config類
@ComponentScan("org.apache.shardingsphere.spring.boot.converter") // 配置掃描路徑,會掃描并注冊相關(guān)spring bean
@EnableConfigurationProperties(SpringBootPropertiesConfiguration.class) // 啟用屬性類,封裝了外部配置文件信息
@ConditionalOnProperty(prefix = "spring.shardingsphere", name = "enabled", havingValue = "true", matchIfMissing = true) // 當(dāng)spring.shardingsphere.enabled 配置項等于true時,加載該自動配置類
@AutoConfigureBefore(DataSourceAutoConfiguration.class) // 在DataSourceAutoConfiguration自動配置類之前配置
@RequiredArgsConstructor // lombok注解
public class SpringBootConfiguration implements EnvironmentAware {
// 屬性類,會自動注入進來
private final SpringBootPropertiesConfiguration props;
private final Map<String, DataSource> dataSourceMap = new LinkedHashMap<>();
// 核心,創(chuàng)建shardingsphere
@Bean
@Autowired(required = false)
public DataSource shardingSphereDataSource(final ObjectProvider<List<RuleConfiguration>> rules) throws SQLException {
Collection<RuleConfiguration> ruleConfigurations = Optional.ofNullable(rules.getIfAvailable()).orElse(Collections.emptyList());
return ShardingSphereDataSourceFactory.createDataSource(dataSourceMap, ruleConfigurations, props.getProps());
}
// 創(chuàng)建spring bean ShardingTransactionTypeScanner
@Bean
public ShardingTransactionTypeScanner shardingTransactionTypeScanner() {
return new ShardingTransactionTypeScanner();
}
// 感知上下文對象,因為自動配置類本身也是一個spring bean,所以這里可以這樣子用
@Override
public final void setEnvironment(final Environment environment) {
dataSourceMap.putAll(DataSourceMapSetter.getDataSourceMap(environment));
}
}
使用也比較簡單,和引入普通的jar包相同,在需要的項目里引入其GAV即可,最終springboot會掃描到spring.facatories,并加載其中的組件,當(dāng)然最重要的自然是自動配置類了,接下來我們仿照shardingsphere 的starter來自定義一個starter。
3:自定義starter
3.1:自定義starter
首先我們來定義屬性類,如下:
@ConfigurationProperties(prefix = "info")
@Getter
@Setter
public class HelloProperties {
// private Properties prop = new Properties();
private String name;
}
即接收的配置的前綴是info,這里的name屬性配置中就可能是info.name=xxxx,接著我們來定義一個我們的starter能夠提供的類Spokesman,該類的功能就是會說話,因此,使用了我們starter就能擁有一個會spoke的man,如下:
@AllArgsConstructor
public class Spokesman {
private String name;
public String speak() {
System.out.println("你好,向大家介紹:" + name);
return name;
}
}
接著就可以定義最重要的自動配置類了,如下:
@Configuration
@EnableConfigurationProperties(HelloProperties.class)
@ConditionalOnExpression // 默認(rèn)為true,即默認(rèn)加載
@AllArgsConstructor
public class HelloAutoConfiguration implements InitializingBean {
private final HelloProperties props;
// 創(chuàng)建 Spokesman 的 spring bean
@Bean
public Spokesman createSpokesman() {
return new Spokesman(props.getName());
}
// 僅僅為了打印props,沒有其他特殊用途
@Override
public void afterPropertiesSet() throws Exception {
System.out.println("props isss: " + props.getName());
}
}
但此時,我們的自動配置類還不能加入到springboot的體系中,還需要在META-INF下創(chuàng)建spring.factories文件,如下:

3.2:使用自定義starter
starter其實也就是一個普通的maven依賴,所以我們想要使用的話,首先需要引入其對應(yīng)的GAV,這里如下:
<dependency>
<groupId>dongshi.daddy</groupId>
<artifactId>hello-starter</artifactId>
<version>1.0-SNAPSHOT</version>
</dependency>
接著我們提供starter需要的配置信息,如下:
info: name: 甜甜的葡萄干
接著我們就可以獲取starter提供的SpokeMan來spoke了,如下:
@Resource
private Spokesman spokesman;
@RequestMapping("/starter")
@ResponseBody
public String starter() {
System.out.println("starter ...");
return spokesman.speak();
}
運行main,如果是在console看到如下輸出,則說明starter已經(jīng)使用成功了:
2023-07-03 21:01:56.508 INFO 3011 --- [ main] w.s.c.ServletWebServerApplicationContext : Root WebApplicationContext: initialization completed in 2355 ms
props isss: 甜甜的葡萄干
...
接著我們就可以訪問//localhost:8899/my/starter了:

到此這篇關(guān)于springboot中的starter及自定義方法詳解的文章就介紹到這了,更多相關(guān)springboot中的starter內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
java的Array,List和byte[],String相互轉(zhuǎn)換的方法你了解嘛
這篇文章主要為大家詳細(xì)介紹了java的Array,List和byte[],String相互轉(zhuǎn)換的方法,文中示例代碼介紹的非常詳細(xì),具有一定的參考價值,感興趣的小伙伴們可以參考一下,希望能夠給你帶來幫助2022-02-02
Java ScheduledExecutorService的具體使用
ScheduledExecutorService有線程池的特性,也可以實現(xiàn)任務(wù)循環(huán)執(zhí)行,本文主要介紹了Java ScheduledExecutorService的具體使用,具有一定的參考價值,感興趣的可以了解一下2023-05-05
解決springboot?druid數(shù)據(jù)庫連接池連接失敗后一直重連問題
這篇文章主要介紹了解決springboot?druid數(shù)據(jù)庫連接池連接失敗后一直重連問題,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2022-11-11

