首页 > 解决方案 > PropertySource 可选用变量命名的属性文件覆盖默认值

问题描述

我在 IntelliJ 上有一个 Serenity-BDD 项目,其中包含 Serenity-Spring 和多个 .properties 文件,一个用于显示每个部署环境(dev、qa、生产)的一个基本 .properties 文件,其中包含 localhost 的变量。

test.properties
test-dev.properties
test-qa.properties
test-prod.properties

我在我的 CLI 命令 (-Denvironment) 中传递一个参数来选择将覆盖基础的 .properties 文件。

./gradlew build -Denvironment

在我的@PropertiesSource 中,我列出了两个文件,以及覆盖文件的环境变量:

@PropertySource(value = {"test.properties", "test-${environment}.properties"}, ignoreResourceNotFound = true)

但是,当我通过 IntelliJ 在本地运行它时(意味着没有 -D 环境变量,意味着 localhost,并且只需要 test.properties 文件),我的输出中出现以下错误:

信息:属性位置 [test-${environment}.properties] 无法解析:无法解析值“test-${environment}.properties”中的占位符“环境”

这个错误到底是什么,解决它的最佳方法是什么?

标签: springproperties-fileserenity-bdd

解决方案


当您硬编码加载两个属性文件的事实时,我将使用 Spring SpEL 默认值机制:

@PropertySource(value = {"test.properties", "test-${environment:local}.properties"})

这样,当没有可用的环境时,Spring 将加载test.propertiestest-local.properties

您有[test-${environment}.properties] 不可解析错误是正常的,因为占位符在PropertySources加载之前已解析(如果您考虑一下,这是逻辑)。

此外,ignoreResourceNotFound = true容易出错,我不建议在生产代码中使用它。

如果您只使用一个文件,您可以使用

@PropertySource("${environment:local}.properties")

这是 Spring 将加载的内容:

  •                                   => local.properties
  • -Denvironment=uat => uat.properties
  • -Denvironment=prod => prod.properties

推荐阅读