如何创建自己的 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>
  3. 创建一个用 @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();
     }
    

    }

  4. 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不推荐使用了》:

https://www.didispace.com/article/spring-boot/spring-boot-factories-deprecations.html

验证测试

在制作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注解来有选择地启用或禁用某些自动配置。

相关推荐
coderWangbuer14 分钟前
基于springboot的高校招生系统(含源码+sql+视频导入教程+文档+PPT)
spring boot·后端·sql
Kenny.志23 分钟前
2、Spring Boot 3.x 集成 Feign
java·spring boot·后端
sky丶Mamba40 分钟前
Spring Boot中获取application.yml中属性的几种方式
java·spring boot·后端
千里码aicood2 小时前
【2025】springboot教学评价管理系统(源码+文档+调试+答疑)
java·spring boot·后端·教学管理系统
程序员-珍2 小时前
使用openapi生成前端请求文件报错 ‘Token “Integer“ does not exist.‘
java·前端·spring boot·后端·restful·个人开发
liuxin334455662 小时前
教育技术革新:SpringBoot在线教育系统开发
数据库·spring boot·后端
代码在改了5 小时前
springboot厨房达人美食分享平台(源码+文档+调试+答疑)
java·spring boot
kylinxjd6 小时前
spring boot发送邮件
java·spring boot·后端·发送email邮件
杨荧6 小时前
【JAVA开源】基于Vue和SpringBoot的旅游管理系统
java·vue.js·spring boot·spring cloud·开源·旅游
surfirst7 小时前
举例说明 .Net Core 单元测试中 xUnit 的 [Theory] 属性的用法
单元测试·.netcore·xunit