Spring Boot中@TestPropertySource无法加载指定YAML属性文件问题
Spring Boot集成测试加载YML配置文件失败问题解决
问题原因@TestPropertySource注解默认仅支持解析.properties格式的配置文件,不识别.yml/.yaml格式。虽然Spring能找到你指定的yml文件,但不会解析其中的配置内容,所以导致${application.profileId}占位符无法被解析。
方案一:使用@ActiveProfiles(推荐)
Spring Boot原生支持多环境配置文件,命名规则为application-{profile}.yml,直接利用这个特性即可:
- 保持
src/test/resources/application-redshift.yml的位置和内容不变 - 修改测试类,移除
@TestPropertySource,添加@ActiveProfiles("redshift")
修改后的测试类代码:
@ExtendWith(SpringExtension.class) @SpringBootTest @ActiveProfiles("redshift") class RedshiftConverterTests { @Value("${application.profileId}") private String profileId; @Test void contextLoads() { System.out.println("profile :: "+profileId); } }
方案二:自定义YamlPropertySourceFactory支持YML文件
如果必须通过@TestPropertySource加载YML文件,需要自定义一个支持YML解析的PropertySourceFactory:
- 实现YamlPropertySourceFactory类:
import org.springframework.beans.factory.config.YamlPropertiesFactoryBean; import org.springframework.core.env.PropertiesPropertySource; import org.springframework.core.env.PropertySource; import org.springframework.core.io.support.EncodedResource; import org.springframework.core.io.support.PropertySourceFactory; import java.io.IOException; import java.util.Properties; public class YamlPropertySourceFactory implements PropertySourceFactory { @Override public PropertySource<?> createPropertySource(String name, EncodedResource resource) throws IOException { YamlPropertiesFactoryBean factory = new YamlPropertiesFactoryBean(); factory.setResources(resource.getResource()); Properties properties = factory.getObject(); return new PropertiesPropertySource(name != null ? name : resource.getResource().getFilename(), properties); } }
- 在测试类的
@TestPropertySource中指定该工厂类:
@ExtendWith(SpringExtension.class) @SpringBootTest @TestPropertySource(locations = "classpath:application-redshift.yml", factory = YamlPropertySourceFactory.class) class RedshiftConverterTests { @Value("${application.profileId}") private String profileId; @Test void contextLoads() { System.out.println("profile :: "+profileId); } }
内容的提问来源于stack exchange,提问作者Shades88
相关产品推荐
相关产品推荐

