跳至主要內容

如何创建自己的Spring Boot Starter并为其编写单元测试

程序猿DD原创Spring BootSpring Boot大约 3 分钟

如何创建自己的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不推荐使用了》open in new window

验证测试

在制作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技术交流群open in new window,参与交流与讨论,更好的学习与进步!更多Spring Boot教程可以点击直达!open in new window,欢迎收藏与转发支持!

最后再给大家推荐一些有关Spring Boot Starter和自动化配置的扩展阅读:

上次编辑于:
贡献者: 程序猿DD