You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用@ExtendWith(SpringExtension.class)加载application.properties配置

Spring Boot 轻量集成测试与自定义切片实现

一、解决@Value获取属性键而非值的问题

只加@ExtendWith(SpringExtension.class)不足以触发Spring的属性解析机制,必须配合上下文初始化配置:

  • 编写测试专用配置类,指定要加载的配置文件和所需Bean:
@Configuration
@PropertySource("classpath:application.properties") // 按需指定配置文件路径
public class TestCoreConfig {
    // 注册测试需要的自定义Bean
    @Bean
    public MyCustomBean customBean() {
        return new MyCustomBean();
    }
}
  • 测试类上添加@ContextConfiguration(classes = TestCoreConfig.class),配合@ExtendWith(SpringExtension.class),此时@Value就能正确解析属性值。

二、处理不存在的属性显示键而非null的问题

默认情况下,Spring无法解析占位符时会保留原字符串,要让不存在的属性返回null:

  • 直接在@Value中使用默认值语法:@Value("${my.nonexistent.prop:null}"),属性不存在时自动注入null
  • 若使用外部配置文件,可在@PropertySource中添加ignoreResourceNotFound = true,避免因配置文件缺失抛出异常
  • 如需全局宽松处理,可在测试配置中添加@Import(ConfigurationPropertiesAutoConfiguration.class),启用配置属性的宽松绑定机制

三、实现类似@JdbcTest的自定义切片测试

自定义切片的核心是通过元注解封装上下文配置、Bean过滤规则,实现按需加载:

  1. 定义切片注解:
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@ExtendWith(SpringExtension.class)
@ContextConfiguration(classes = CustomSliceAutoConfig.class)
@AutoConfigureExcludeFilter // 排除默认自动配置中不需要的部分
@TypeExcludeFilters(CustomSliceFilter.class) // 自定义Bean过滤规则
public @interface CustomSliceTest {
}
  1. 编写Bean过滤类,排除不需要的组件:
public class CustomSliceFilter extends TypeExcludeFilter {
    @Override
    public boolean match(MetadataReader metadataReader, MetadataReaderFactory metadataReaderFactory) throws IOException {
        String className = metadataReader.getClassMetadata().getClassName();
        // 按需排除Controller、Repository等非核心组件
        return className.endsWith("Controller") || className.contains("Repository");
    }
}
  1. 编写切片自动配置类,加载必要的配置和Bean:
@Configuration
@PropertySource("classpath:application.properties")
@ConfigurationPropertiesScan(basePackages = "com.yourproject.config.props") // 扫描配置属性绑定类
public class CustomSliceAutoConfig {
    // 导入必要的自动配置类,比如配置属性处理
    @Import(ConfigurationPropertiesAutoConfiguration.class)
    static class InnerConfig {}

    // 注册切片测试需要的核心Bean
    @Bean
    public MyService myService() {
        return new MyService();
    }
}
  1. 使用自定义切片测试:
@CustomSliceTest
public class CustomSliceDemoTest {
    @Value("${app.core.version}")
    private String appVersion;

    @Autowired
    private MyService myService;

    @Test
    void testCoreLogic() {
        // 测试自定义Bean和属性加载逻辑
    }
}

内容的提问来源于stack exchange,提问作者theMyth

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.17 21:56:10