一、簡介
Spring Boot Starter是Spring Boot生態中非常重要的一部分,它允許開發者通過簡單的依賴管理來快速集成各種功能和庫。在開發過程中,我們經常會遇到一些通用的功能或配置,如果每次都需要手動添加這些配置和依賴,那么將會非常繁瑣。因此,創建一個自定義的Spring Boot Starter可以極大地提高開發效率。本文將詳細介紹如何創建自己的Spring Boot Starter,并為其編寫單元測試。
二、創建Spring Boot Starter
1. 初始化項目
使用Spring Initialize(https://start.spring.io/)或Maven/Gradle手動創建一個新的Spring Boot項目,并選擇需要的依賴(通常不需要選擇太多,因為我們只是創建一個starter)。
<dependencies><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter</artifactId></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-autoconfigure</artifactId></dependency>
</dependencies>
2. 定義自動配置
在src/main/java目錄下,創建一個新的包(例如com.example.mystarter.autoconfigure),并在其中添加自動配置類。這個類需要使用@Configuration和@EnableAutoConfiguration注解,并可能需要定義一些@Bean方法。
package com.example.mystarter.autoconfigure; import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Bean; @Configuration
@EnableAutoConfiguration
public class MyStarterAutoConfiguration { @Bean public MyService myService() { return new MyServiceImpl(); }
}
3.創建spring.factories文件(Spring Boot 2.7 以下)
在src/main/resources/META-INF目錄下創建spring.factories文件,并在org.springframework.boot.autoconfigure.EnableAutoConfiguration關鍵字下列出您的自動配置類,比如:
org.springframework.boot.autoconfigure.EnableAutoConfiguration=\
com.example.mystarter.autoconfigure.MyStarterAutoConfiguration
該配置的作用是讓Spring Boot應用在引入您自定義Starter的時候可以自動這里的配置類。
4. Spring Boot 2.7 新特性
Spring Boot 2.7開始,不再推薦使用spring.factories,而是創建新的文件:
/META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports
文件內容直接放需要自動加載配置類路徑即可,比如這樣:
com.example.mystarter.autoconfigure.MyStarterAutoConfiguration
注意:這里多了一級spring目錄。
三、驗證測試
在制作Spring Boot Starter的時候,一定記得使用單元測試來驗證和確保自動化配置類在任何條件邏輯在啟動器下能夠按照正確的預期運行。
1. 添加測試依賴
在pom.xml或build.gradle文件中添加測試相關的依賴,例如Spring Boot Test、JUnit等。
<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-test</artifactId><scope>test</scope></dependency>
2. 創建單元測試
使用@SpringBootTest加載完整的應用程序上下文,并驗證啟動程序是否正確配置了 Bean 和屬性。
package com.example.mystarter; import com.example.mystarter.autoconfigure.MyStarterAutoConfiguration;
import com.example.mystarter.service.MyService;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest; import static org.junit.jupiter.api.Assertions.assertNotNull; @SpringBootTest(classes = MyStarterAutoConfiguration.class)
public class MyStarterAutoConfigurationTest { @Autowired private MyService myService; @Test public void testMyService() { assertNotNull(myService, "MyService should not be null"); // 這里可以添加更多的測試邏輯 }
}
參考:
https://segmentfault.com/a/1190000020121457