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

使用ContextConfiguration时ConfigurationProperties无法加载问题排查

解决Spring Boot项目中测试类@ConfigurationProperties加载失败的问题

这个问题我遇过好几次了——你现在的测试用的还是传统Spring Framework的测试方式,没跟上Spring Boot的自动配置节奏,所以@ConfigurationProperties才会加载失败。咱们一步步来解决:

核心原因

原来的测试依赖SpringJUnit4ClassRunner和@ContextConfiguration加载XML配置,但这套组合不会触发Spring Boot的自动配置机制,而@ConfigurationProperties的解析、绑定正是Spring Boot自动配置的一部分,自然就失效了。

具体解决方案

1. 替换测试核心注解,启用Spring Boot上下文

把原来的@RunWith和@ContextConfiguration换成Spring Boot专属的@SpringBootTest注解。这个注解会自动启动完整的Spring Boot上下文,包含所有自动配置逻辑,包括@ConfigurationProperties的处理。

2. 保留原有XML配置(如果需要)

如果你还依赖applicationContextTestFnx.xml里的Derby数据源和组件,不要直接丢了,用@ImportResource导入即可,替代原来的@ContextConfiguration:

@SpringBootTest
@ImportResource("classpath:applicationContextTestFnx.xml")
public class YourTestClass {
    // 你的测试代码
}

3. 调整TestExecutionListeners(按需)

原来的@TestExecutionListeners里的监听器,Spring Boot的@SpringBootTest已经默认包含了大部分(比如DependencyInjectionTestExecutionListener、DirtiesContextTestExecutionListener)。如果必须保留DbUnitTestExecutionListener这类自定义监听器,手动指定时一定要加上SpringBootTestExecutionListener——这是Spring Boot自动配置的关键监听器,丢了的话@ConfigurationProperties还是会失效:

@SpringBootTest
@ImportResource("classpath:applicationContextTestFnx.xml")
@TestExecutionListeners({
    SpringBootTestExecutionListener.class, // 必须加这个!
    DependencyInjectionTestExecutionListener.class,
    DirtiesContextTestExecutionListener.class,
    TransactionalTestExecutionListener.class,
    DbUnitTestExecutionListener.class
})
public class YourTestClass {
    // 你的测试代码
}

4. 检查@ConfigurationProperties类的配置

确保你的配置类本身没问题:

  • 类上标注了@ConfigurationProperties(prefix = "xxx")(替换成你的配置前缀)
  • 要么这个类在Spring Boot的组件扫描路径下,要么用@EnableConfigurationProperties(YourConfigClass.class)手动启用绑定

进阶建议(可选)

如果有精力,建议逐步把XML里的配置迁移到Spring Boot的application-test.properties(或yaml)中,配合@ConfigurationProperties绑定,这是Spring Boot的最佳实践:

比如原来XML里的Derby数据源配置,改成application-test.properties:

spring.datasource.url=jdbc:derby:memory:testdb;create=true
spring.datasource.username=test
spring.datasource.password=test
spring.datasource.driver-class-name=org.apache.derby.jdbc.EmbeddedDriver

然后用一个配置类绑定:

@ConfigurationProperties(prefix = "spring.datasource")
public class DataSourceProperties {
    private String url;
    private String username;
    private String password;
    private String driverClassName;

    // getter、setter
}

这样测试代码可以完全去掉XML依赖,更简洁也更符合Spring Boot的生态。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.21 04:25:14