構建自己的 Spring Boot Starter
Starter 優勢
依賴聚合:Spring Boot Starter 將一系列相關的依賴項打包成一個單一的依賴項,簡化了項目的依賴管理。開發者只需引入一個 Starter,即可獲得所需的所有相關依賴,無需手動逐一添加。
自動配置:Starter 內置了基于 @Conditional 注解的配置類,能夠根據項目的運行環境(例如類路徑中是否存在特定的類)自動創建并裝配 Bean。這種機制極大地減少了手動配置的工作量,使得開發者能夠更專注于業務邏輯的實現。
通過這兩大優勢,Spring Boot Starter 顯著提升了開發效率,降低了配置復雜度,使得項目的搭建和維護更加便捷。
如何構建屬于自己 Starter
根據配置自動裝配一個SimpleDateFormat
1. 新建 Spring Boot 項目

2. 創建

DateFormatProperties :
import org.springframework.boot.context.properties.ConfigurationProperties;
@ConfigurationProperties("formatter") // 匹配 formatter 前綴的配置
public class DateFormatProperties {
private String pattern = "yyyy-MM-dd HH:mm:ss";
public String getPattern() {
return pattern;
}
public void setPattern(String pattern) {
this.pattern = pattern;
}
}
DateFormatConfiguration :
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import java.text.SimpleDateFormat;
@Configuration
@EnableConfigurationProperties(DateFormatProperties.class) // 掃描 DateFormatProperties,注冊為bean
@ConditionalOnProperty(prefix = "formatter", name = "enabled", havingValue = "true") // 當且 formatter.enabled = true 才會被加載
public class DateFormatConfiguration {
private final DateFormatProperties dateFormatProperties;
public DateFormatConfiguration(DateFormatProperties dateFormatProperties) {
this.dateFormatProperties = dateFormatProperties;
}
@Bean(name = "myDateFormatter")
public SimpleDateFormat myDateFormatter() {
return new SimpleDateFormat(dateFormatProperties.getPattern());
}
}
spring.factories : 這里需要替換為實際自己的類路徑
org.springframework.boot.autoconfigure.EnableAutoConfiguration=org.tao.config.DateFormatConfiguration
使用maven工具打包成jar包:
mvn clean install
3. 新項目中使用
pom文件中添加依賴:
<dependency>
<groupId>org.tao</groupId>
<artifactId>tao-spring-boot-starter</artifactId>
<version>1.0-SNAPSHOT</version>
</dependency>
application.properties:
formatter.enabled = true
formatter.pattern = yyyy-MM-dd
啟動Spring項目,SimpleDateFormat 就自動被 Spring 進行管理。
總結步驟
- 引入 spring-boot-autoconfigure 依賴
- 創建配置實體類
- 創建自動配置類,設置實例化條件(@Conditionalxxx注解,可不設置),并注入容器
- 在 MATE-INF 文件夾下創建 spring.factories 文件夾,激活自動配置。
- 在 maven 倉庫發布 starter
附錄
關于Spring 自動裝配
2.7.x之前:resources 下增加META-INF文件夾,創建spring.factories文件
org.springframework.boot.autoconfigure.EnableAutoConfiguration=\
com.handsometaoa.config.SmsConfig
2.7.x之后:resources 下增加META-INF文件夾,在其下創建spring文件夾,最后創建
org.springframework.boot.autoconfigure.AutoConfiguration.imports文件
com.handsometaoa.config.SmsConfig
本文來自博客園,作者:帥氣的濤啊,轉載請注明原文鏈接:http://www.rzrgm.cn/handsometaoa/p/18779874

浙公網安備 33010602011771號