spring - 用外部属性覆盖 spring-boot application.properties
问题描述
我有一个弹簧启动应用程序。我有 3 个属性文件:
spring-boot jar 中的一个属性文件 - myjar.jar称为 application.properties (它是 jar 中的包)
jar 外部的属性文件,位于配置/global.properties下的 jar 位置
jar 外部的属性文件,位于配置/java.properties下的 jar 位置
问题是,我正在运行以下命令:
java -Dlogging.config=logback.xml -jar "myjar.jar" spring.config.location=classpath:/application.properties,file:./configurations/global.properties,file:./configurations/java.properties
我得到一个例外:
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'myApplication': Injection of autowired dependencies failed; nested exception is java.lang.IllegalArgumentException: Could not resolve placeholder 'Data.StoresDb.LakeConnectionString' in value "${Data.StoresDb.LakeConnectionString}"
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessProperties(AutowiredAnnotationBeanPostProcessor.java:405)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1422)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:594)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:517)
at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:323)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:222)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:321)
at org.springframework.beans.fa
在myApplication.java 中,我有:
@Value("${Data.StoresDb.LakeConnectionString}")
String dataLakeStoreDb;
在我的application.properties中我没有Data.StoresDb.LakeConnectionString,但我的global.properties中有它,我希望spring在尝试提供值Data.StoresDb.LakeConnectionString之前解析所有文件
解决方案
您将 arg/值作为原始 Java 参数传递:
java -jar "myjar.jar" spring.config.location=...
该参数将出现在String[] args
主类中,但 Spring 环境不会意识到这一点。
您必须在它前面加上前缀--
才能使参数能够感知 Spring 环境:
java -jar "myjar.jar" --spring.config.location=...
从官方文档:
默认情况下,SpringApplication 会将任何命令行选项参数(以“--”开头,例如 --server.port=9000)转换为属性并将其添加到 Spring 环境
或者作为替代将其作为系统属性传递:
java -Dspring.config.location=... -jar "myjar.jar"
附带说明:当在 Spring Boot 2 中引入时,请注意spring.config.location
覆盖默认位置,spring.config.additional-location
将指定位置添加到默认位置。
推荐阅读
- mysql - 为什么ansible无法连接MySql?
- katalon-studio - Katalon Analytics 未显示从测试集合执行的所有测试套件的结果
- c# - 从可观察集合中绑定组合框项目源时遇到问题
- java - 使用 ContentCachingRequestWrapper 后缺少所需的请求正文
- javascript - 在服务器上创建 Zip 存档并在客户端下载
- jena - 有谁知道如何让 tdb2.dump 命令真正做任何事情
- sql - 在 oracle sql 中从包含 XML 格式字符串的列中获取子字符串
- apache-spark - 如何将多个列作为参数传递给 Spark 数据框
- express - Vue.js devServer.proxy 的问题
- r - 用 R 中的另一个特定模式重命名多个文件的特定模式