如何創建自己的Spring Boot Starter併爲其編寫單元測試

當我們想要封裝一些自定義功能給別人使用的時候,創建Spring Boot Starter的形式是最好的實現方式。如果您還不會構建自己的Spring Boot Starter的話,本文將帶你一起創建一個自己的Spring Boot Starter。

快速入門

  1. 創建一個新的 Maven 項目。第三方封裝的命名格式是 xxx-spring-boot-starter ,例如:didispace-spring-boot-starter

  2. 編輯pom.xml,添加spring-boot-autoconfigurespring-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>
  1. 創建一個用 @Configuration 註釋的配置類,在這裏您可以使用@Bean來創建使用@ConditionalOnClass@ConditionalOnMissingBean等條件註釋來控制何時應用配置。
@Configuration
@ConditionalOnClass(MyFeature.class)
@ConditionalOnProperty(prefix = "myfeature", name = "enabled", matchIfMissing = true)
public class MyFeatureAutoConfiguration {

    @Bean
    @ConditionalOnMissingBean
    public MyFeature myFeature() {
        return new MyFeature();
    }
}
  1. src/main/resources/META-INF目錄下創建spring.factories文件,並在org.springframework.boot.autoconfigure.EnableAutoConfiguration關鍵字下列出您的自動配置類,比如:
org.springframework.boot.autoconfigure.EnableAutoConfiguration=\
com.didispace.myfeature.MyFeatureAutoConfiguration

該配置的作用是讓Spring Boot應用在引入您自定義Starter的時候可以自動這裏的配置類。

注意:Spring Boot 2.7開始,不再推薦使用spring.factories,而是改用/META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports,文件內容直接放需要自動加載配置類路徑即可。這個變更具體可見之前的這篇文章:《Spring Boot 2.7開始spring.factories不推薦使用了》

驗證測試

在製作Spring Boot Starter的時候,一定記得使用單元測試來驗證和確保自動化配置類在任何條件邏輯在啓動器下能夠按照正確的預期運行。

創建單元測試

使用@SpringBootTest加載完整的應用程序上下文,並驗證啓動程序是否正確配置了 Bean 和屬性。

@SpringBootTest(classes = TestApplication.class)
public class MyStarterAutoConfigurationTest {

    @Autowired(required = false)
    private MyService myService;

    @Test
    public void testMyServiceAutoConfigured() {
        assertNotNull(myService, "MyService should be auto-configured");
    }
}

覆蓋不同的配置

如果有不同的配置方案,那麼還需要使用@TestPropertySource@DynamicPropertySource覆蓋屬性以測試不同配置下的情況。

或者也可以直接簡單的通過@SpringBootTest中的屬性來配置,比如下面這樣:

@SpringBootTest(properties = "my.starter.custom-property=customValue")
public class MyStarterPropertiesTest {

    @Value("${my.starter.custom-property}")
    private String customProperty;

    @Test
    public void testPropertyOverride() {
        assertEquals("customValue", customProperty, "Custom property should be overridden by @SpringBootTest");
    }
}

覆蓋@Conditional的不同分支

如果您的啓動器包含條件配置,比如:@ConditionalOnProperty@ConditionalOnClass等註解,那麼就必須編寫測試來覆蓋所有條件以驗證是否已正確。

比如下面這樣:

@SpringBootTest(classes = {TestApplication.class, MyConditionalConfiguration.class})
@ConditionalOnProperty(name = "my.starter.enable", havingValue = "true")
public class MyStarterConditionalTest {

    @Autowired
    private ApplicationContext context;

    @Test
    public void conditionalBeanNotLoadedWhenPropertyIsFalse() {
        assertFalse(
            context.containsBean("conditionalBean"),
            "Conditional bean should not be loaded when 'my.starter.enable' is false"
        );
    }
}

爲了覆蓋不同的條件分支,我們通常還需要使用@TestConfiguration註解來有選擇地啓用或禁用某些自動配置。

小結

本文介紹了兩個Spring Boot的進階內容:

  1. 如何創建 Spring Boot Starter
  2. 如何爲 Spring Boot Starter 提供單元測試

掌握這項技能可以幫你更好的爲Spring Boot提供模塊劃的功能封裝。如果您學習過程中如遇困難?可以加入我們超高質量的Spring技術交流羣,參與交流與討論,更好的學習與進步!更多Spring Boot教程可以點擊直達!,歡迎收藏與轉發支持!

最後再給大家推薦一些有關Spring Boot Starter和自動化配置的擴展閱讀:

歡迎關注我的公衆號:程序猿DD。第一時間瞭解前沿行業消息、分享深度技術乾貨、獲取優質學習資源

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章