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

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:

  1. 实现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);
    }
}
  1. 在测试类的@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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.26 11:30:16