Spring Boot 3.2.1测试无法注入测试配置文件属性,求排查
问题原因及解决方法
你的问题出在以下几个地方:
- 未使用Spring Boot专属的测试启动注解,导致Spring Boot的自动配置机制未生效,无法正确加载测试环境的配置文件。
- 手动创建了
PropertySourcesPlaceholderConfigurerBean,这是多余的操作——Spring Boot已经自动配置了该属性处理器,手动添加反而会干扰默认的属性加载逻辑。
修正后的测试代码
import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Value; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.ActiveProfiles; @SpringBootTest @ActiveProfiles("test") public class ConfigPropertiesTest { @Value("${myapp.server}") String server; @Test void test() { System.out.println(server); // 现在可以正常输出属性值 } }
额外注意事项
- 确保测试配置文件命名为
application-test.properties,且放置在src/test/resources目录下,这样@ActiveProfiles("test")才能正确识别并加载它。 - 若你不想使用
@SpringBootTest(比如只想加载部分配置),可以改用@TestPropertySource指定配置文件路径,同时保留@ContextConfiguration,但必须移除配置类中的PropertySourcesPlaceholderConfigurerBean以避免冲突,示例如下:
import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.springframework.beans.factory.annotation.Value; import org.springframework.context.annotation.Configuration; import org.springframework.test.context.ActiveProfiles; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.TestPropertySource; import org.springframework.test.context.junit.jupiter.SpringExtension; @ExtendWith(SpringExtension.class) @ContextConfiguration(classes = ConfigPropertiesTestConfig.class) @ActiveProfiles("test") @TestPropertySource(locations = "classpath:application-test.properties") public class ConfigPropertiesTest { @Value("${myapp.server}") String server; @Test void test() { System.out.println(server); } @Configuration static class ConfigPropertiesTestConfig { // 移除手动创建的PropertySourcesPlaceholderConfigurer Bean } }
内容的提问来源于stack exchange,提问作者Sergey Zolotarev
相关产品推荐
相关产品推荐

