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

存在application.properties时@PropertySource为何失效?如何解决?

问题原因分析

你遇到的这个问题其实是Spring Boot属性加载优先级导致的——默认的application.properties优先级比通过@PropertySource指定的配置文件更高。

Spring Boot加载属性的顺序是有明确规则的,简单来说:

  • 命令行参数 > 系统环境变量 > 外部配置文件 > 内部application.properties/yml > 通过@PropertySource加载的配置文件

所以当application.properties和test.properties存在相同的配置项(比如test.name)时,高优先级的application.properties的值会覆盖低优先级的test.properties的值,这就是为什么你看到输出myNameBad的原因。

解决方案

下面给你几种可行的解决方法,你可以根据自己的需求选择:

方法1:移除application.properties中的重复配置项

这是最简单直接的方式——如果不需要application.properties里的test.name配置,直接删掉这个条目,Spring就会自动读取test.properties里的test.name=myNameGood。

方法2:自定义属性源优先级,让test.properties优先

如果你需要保留application.properties,同时让test.properties的配置优先级更高,可以通过自定义PropertySourcesPlaceholderConfigurer来调整加载顺序:

  1. 先修改你的DemoProperties,去掉@PropertySource注解(因为我们要手动加载配置文件):
@Component
@ConfigurationProperties("test")
public class DemoProperties {
    private String name;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
}
  1. 创建一个新的配置类,手动加载test.properties并设置更高的优先级:
@Configuration
public class CustomPropertyConfig {
    @Bean
    public PropertySourcesPlaceholderConfigurer propertySourcesPlaceholderConfigurer() {
        PropertySourcesPlaceholderConfigurer configurer = new PropertySourcesPlaceholderConfigurer();
        // 指定要加载的配置文件
        configurer.setLocation(new ClassPathResource("test.properties"));
        // 设置优先级为0(数字越小优先级越高),确保它比application.properties先被加载
        configurer.setOrder(0);
        return configurer;
    }
}

这样修改后,test.properties的配置会覆盖application.properties中的同名项,测试时就会输出myNameGood。

方法3:指定Spring Boot的主配置文件名

如果你想让test.properties作为主配置文件,可以在启动应用时添加参数:

--spring.config.name=test

这样Spring Boot会优先加载test.properties,而不是默认的application.properties。如果需要同时加载两个配置文件,可以指定多个名称:

--spring.config.name=application,test

不过要注意,这种情况下application.properties的优先级还是高于test.properties,所以如果有重复配置,还是会用application.properties的值。

验证测试

修改完成后,重新运行你的测试类ApplicationTests,就能看到输出预期的myNameGood啦~

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.15 06:35:10