【问题标题】:Override Properties file in Spring WebApp at Runtime在运行时覆盖 Spring WebApp 中的属性文件
【发布时间】:2016-01-16 01:15:24
【问题描述】:

我正在使用 PropertyPlaceholderConfigurer 在我的 Spring WebApplication 中加载属性文件,如下所示:

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

现在,我想覆盖 mail.properties 中的一些属性,所以我在我的 application-context 文件中创建了一个额外的条目来读取这个 post,如下所示:

<context:property-placeholder location="file:override.properties"
        order="-1" ignore-unresolvable="true" ignore-resource-not-found="true" />

然后,在我的 Tomcat Server 中,在启动配置的 VM Arguments 中,我提供了额外的条目:

-Dexternal.props="/Users/ArpitAggarwal/Desktop/override.properties"

对于一些我必须覆盖的键的覆盖值。

但是,WebApp 没有获取来自override.properties 的值。谁能帮我弄清楚我错过了什么。

任何帮助将不胜感激。谢谢!

【问题讨论】:

    标签: java spring spring-mvc tomcat properties-file


    【解决方案1】:

    我认为使用多个 propertyPlaceholders 并不是一个好主意。 当两个 xml 配置在同一上下文中加载每个属性并尝试交叉使用它们时,我遇到了很多问题。

    如果你想外部化一个属性文件,我会建议一个 JNDI 属性:

    <bean
        class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
        <property name="locations">
            <list>
                <value>classpath:db.properties</value>
                <value>classpath:mail.properties</value>
                <value>${java:com/env/myApp/externalProperties}
            </list>
        </property>
    </bean>
    

    此 JNDI 的值将是:“file:/path-to-propertiesFile”。

    这样你只需要一个propertyePlaceholder。 另请注意,通过将外部文件作为最后一个位置,如果您有重复的键,spring 将只保留最后一个。

    【讨论】:

      【解决方案2】:

      你只是在你的应用程序上下文中使用

      <context:property-placeholder location="file:///${external.props}"
          order="-1" ignore-unresolvable="true" ignore-resource-not-found="true" />
      

      问题是你用错了位置,实际位置是 vm arg variable key => ${external.props}

      【讨论】:

      • 这强制要求从服务器提供override.properties 作为vm arg
      【解决方案3】:

      我解决问题的方法是将location属性替换为${ext.properties.dir:classpath:}/override.properties,如下:

      <context:property-placeholder
              location="${ext.properties.dir:classpath:}/override.properties" order="-1"
              ignore-unresolvable="true" ignore-resource-not-found="true" />
      

      并提供来自application-server/jvmext.properties.dir 值:

      -Dext.properties.dir=file:/Users/ArpitAggarwal/properties/
      

      参考6-tips-for-managing-property-files-with-spring.

      【讨论】:

        猜你喜欢
        • 2012-02-08
        • 2017-10-14
        • 2015-03-11
        • 2014-10-28
        • 2013-01-09
        • 2012-09-05
        • 1970-01-01
        • 1970-01-01
        • 2016-08-07
        相关资源
        最近更新 更多