Spring引导类路径配置文件覆盖外部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

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

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

只需更改导入顺序即可。类似于:

<context:property-placeholder file-encoding="UTF-8"
location="${YOUR_CUSTOM_PATH}/global.properties ,
${YOUR_CUSTOM_PATH}/local.properties" ignore-unresolvable="true"/>

@PropertySource(value = {"classpath:global.properties" , "local.properties"},ignoreResourceNotFound = true)

在这种情况下,local.properties覆盖global.properties的属性

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

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

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

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

这是Spring Boot的默认行为。所以你只需要正确地启用它。

首先,删除下一个注释,它们可能会破坏/覆盖默认机制:

@PropertySources({ //
@PropertySource("classpath:application.properties"), //
@PropertySource(value = "file:${external.config}", ignoreResourceNotFound = true) //
})

然后指定文件的位置作为命令行参数:

java -jar myapp.jar --spring.config.additional-location=/this/is/an/external/dir/

更多信息请点击此处:

  • Spring Boot功能-外部化配置
  • 通用应用程序属性-核心属性

然后将您的配置重命名为application.properties,或者通过另一个环境变量指定dev配置文件(文件名中的后缀(:

-Dspring-boot.run.profiles=dev

相关问题:在春季启动中从命令行设置活动配置文件和配置位置

最新更新