【问题标题】:Spring boot - Externalize config propertiesSpring Boot - 外部化配置属性
【发布时间】:2015-09-23 06:46:54
【问题描述】:

我的应用程序是一个带有嵌入式 tomcat 的 Spring Boot 应用程序。它使用一个名为“config.properties”的属性文件来存储各种应用程序级别的属性。我在我的应用程序中加载属性文件:

<bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
    <property name="location">
        <value>classpath:config.properties</value>
    </property>
</bean>

当属性文件嵌入到 jar 文件中时,应用程序工作正常,但我想外部化属性文件 - 从系统中的文件夹而不是 jar 提供它。

我尝试将文件夹添加到类路径,然后使用 -cp vm 参数提供文件夹的位置,但这不起作用。

所以我的问题是如何实现从外部源提供属性文件而不是从 jar 中提供的这种情况。

【问题讨论】:

  • 如果是弹簧启动,只需使用application.properties,您就会得到out-of-the-box 的这种行为。使用不在它周围的框架。基本上删除您的占位符配置器,将属性移动到application.properties。重启。

标签: java spring-boot classpath


【解决方案1】:

我已经能够使用以下代码加载文件:

<bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
    <property name="location">
        <value>file:{config.file.location}/config.properties</value>
    </property>
</bean>

并使用 -

启动 jar
java -jar -Dconfig.file.location=D:\folder\ myjar.jar

【讨论】:

  • 分享你的答案;)
【解决方案2】:

使用此代码:

<bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
    <property name="location">
        <value>file:/full/path/to/your/file</value>
    </property>
</bean>

使用“文件”可以指定配置文件所在的完整路径。

编辑: 如果您想使用内联参数,请删除 bean PropertyPlaceholderConfigurer 并改用它:

-Dspring.config.location=file:/path/to/file/config.properties

【讨论】:

  • 这种方法的问题是我不能动态改变位置,它变成了位置特定和机器特定的。
  • 是的。我知道,但通常你在所有包含配置文件的机器上都有一个特定的文件夹。如果您不想硬编码文件路径,请使用 JVM 参数:-Dspring.config.location=file:/path/to/file
  • 如果我使用这种方法,是否需要更改 PropertyPlaceHolderConfigurer 声明中的任何内容?你能给我举个例子吗?
  • @RachitAgrawal 告诉我们这是否对您有帮助。
猜你喜欢
  • 2019-08-17
  • 2017-08-18
  • 2017-06-21
  • 2018-02-21
  • 2021-01-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-02-25
相关资源
最近更新 更多