首页 > 解决方案 > Spring Boot 类路径配置文件覆盖外部 application.properties

问题描述

我想让 Spring 加载一个外部配置文件(如果存在),否则使用 src/main/resources 中提供的一次。

当前设置:

src/main/resources/application.properties
src/main/resources/application-dev.properties
src/main/resources/application-prod.properties

/this/is/an/external/dir/application-dev.properties

https://stackoverflow.com/a/27776123/5126654类似,我添加了以下注释:

@EnableFeignClients
@SpringBootApplication
@EnableEncryptableProperties
@PropertySources({ //
    @PropertySource("classpath:application.properties"), //
    @PropertySource(value = "file:${external.config}", ignoreResourceNotFound = true) //
})
public class Application extends SpringBootServletInitializer {

   // ....
}

并在我的 application.properties 中有以下条目:

external.config=/this/is/an/external/dir/application-dev.properties

我还可以看到外部配置文件被拾取。我遇到的问题是类路径属性文件中的每个条目都会覆盖外部条目。即,不是从 /this/is/an/external/dir/application-dev.properties 获取条目,而是从 src/main/resources/application-dev.properties 获取条目。

如何修改我的代码以使外部文件覆盖类路径文件的条目?

标签: javaspringspring-boot

解决方案


由于您只需要用于开发的外部配置,因此您也可以考虑在项目的 IDE 运行配置中将外部属性源设置为命令行参数。

--spring.config.location=/this/is/an/external/dir/application-dev.properties

以上述方式指定的属性源会覆盖类路径中存在的 application.properties。


推荐阅读