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

Spring不使用spring.config.location覆盖application.properties问题

Spring Boot外部属性无法覆盖打包后application.properties中的值

背景

我需要覆盖打包后application.properties中定义的部分属性:

my_name=initialValue

但无法获取到my_name的外部值。由于应用部署在包含多个其他应用的Tomcat中,不能使用spring.config.location,否则可能影响其他部署的应用。

已尝试的方案

  1. 通过@Configuration加载属性:
@Configuration
@PropertySources({
       @PropertySource("classpath:application.properties"),
       @PropertySource("file:${external_dir}/my_externalfile.properties"),
}
)
public class AppConfig {

   @Value("${my_name}")
   private String myName;

   @Value("${other}")
   private String other;
}
  1. 声明了如下Bean:
@Bean 
public static PropertySourcesPlaceholderConfigurer PropertySourcesPlaceholderConfigurer() { 
    return new PropertySourcesPlaceholderConfigurer();
}

现象:my_name始终保留默认值,但未在application.properties中定义的other属性能正常从外部文件加载对应值。这种行为是否正常?我原本期望外部属性能直接覆盖默认值。

临时解决方法

我通过在application.properties中声明占位符解决了问题:

my_name=${var_external_placeholder}

同时在外部文件中设置:

var_external_placeholder=ExternalValue

疑问

根据Spring官方文档中的以下内容:

  1. @Configuration类上的@PropertySource注解。请注意,这类属性源要等到应用上下文刷新时才会添加到Environment中。对于某些在刷新开始前就会读取的属性(比如logging.和spring.main.)来说,这就太晚了。
  2. 配置数据(比如application.properties文件)。

这种通过占位符实现覆盖的方式是否符合Spring的设计规范?看起来配置数据会覆盖@PropertySource定义的值,如果不是这样,那么定义@PropertySource的目的是什么?


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.29 17:01:06