SpringBoot 2.7使用@PropertySource加载多YML文件启动失败排查
问题原因及解决办法
核心原因1:@PropertySource 默认不支持 YAML 文件
SpringBoot 2.7 中,@PropertySource 注解原生仅支持 .properties 格式配置文件,无法直接识别 .yml/.yaml 文件。直接用它加载 YAML 文件,不仅无法解析配置内容,还会触发路径解析异常。
核心原因2:多Profile激活导致路径拼接错误
从错误信息 application-default,dev.yml 能看出,你当前激活了多个 Profile(default 和 dev,用逗号分隔)。@PropertySource 解析 ${spring.profiles.active} 时,会直接将逗号分隔的多个值代入路径,生成了不符合预期的文件名,而非你想要的 application-dev.yml。
正确的 YAML 配置加载方式
方案1:自定义工厂支持 YAML 加载
- 编写 YAML 属性源工厂类:
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(resource.getResource().getFilename(), properties); } }
- 在配置类中指定工厂加载文件:
@Configuration @PropertySource(value = {"classpath:application.yml", "classpath:application-${spring.profiles.active}.yml"}, factory = YamlPropertySourceFactory.class) @ConfigurationProperties public class CustomConfig { // 配置属性映射逻辑 }
方案2:利用 SpringBoot 原生 Profile 机制
SpringBoot 会自动加载 application.yml 和 application-{profile}.yml,无需手动通过 @PropertySource 指定。只需激活目标 Profile 即可:
- 在
application.yml中配置:
spring: profiles: active: dev
- 或启动时添加 JVM 参数:
-Dspring.profiles.active=dev
SpringBoot 会自动合并基础配置与对应 Profile 的配置内容。
内容的提问来源于stack exchange,提问作者H.BENIZID
相关产品推荐
相关产品推荐

