spring - 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”中的占位符“环境”
这个错误到底是什么,解决它的最佳方法是什么?
解决方案
当您硬编码加载两个属性文件的事实时,我将使用 Spring SpEL 默认值机制:
@PropertySource(value = {"test.properties", "test-${environment:local}.properties"})
这样,当没有可用的环境时,Spring 将加载test.properties和test-local.properties。
您有[test-${environment}.properties] 不可解析错误是正常的,因为占位符在PropertySources
加载之前已解析(如果您考虑一下,这是逻辑)。
此外,ignoreResourceNotFound = true
容易出错,我不建议在生产代码中使用它。
如果您只使用一个文件,您可以使用
@PropertySource("${environment:local}.properties")
这是 Spring 将加载的内容:
- => local.properties
- -Denvironment=uat => uat.properties
- -Denvironment=prod => prod.properties
推荐阅读
- reactjs - Semantic UI React:如何使 Tab 菜单使用容器的全宽?
- r - 从多边形R中的边缘创建从质心到20 m的缓冲区
- ruby - 为什么 ruby 不能使用大多数 2^X 数字作为对象 ID?
- azure - 训练马拉地语的基线模型失败
- java - org.springframework.data.mongodb.core.mapping.Document 无法引用
- python - 使用单词表达式列表提取文本中的句子并没有真正起作用
- python - 使用输入的种子点过滤双阈值图像
- javascript - 更改图像原型
- django - django模型对年度付款计划的建议
- javascript - 在jQuery中将输入值从一个输入复制到第二个输入