【问题标题】:Spring properties file setting default valuesSpring属性文件设置默认值
【发布时间】:2011-09-16 12:43:09
【问题描述】:

我的 war 文件之外有一个属性文件,系统管理员使用它来关闭某些系统功能。它在我的本地机器上运行得很好,但是当我们部署到开发环境时,属性文件没有上传,应用程序无法启动。我想知道是否有办法在我的 applicationContext 中为通常来自属性文件的值声明默认值。

我目前有这个来读取属性文件:

<util:properties id="myProperties" location="file:${catalina.home}/webapps/myProperties.properties"/>

只要我们记得将属性文件放在正确的位置,它就可以正常工作。有没有办法声明默认值,或者如果找不到这个文件,可以从不同的文件中读取?

谢谢

【问题讨论】:

    标签: java spring configuration properties


    【解决方案1】:

    不要使用&lt;util:properties&gt;,而是使用PropertiesFactoryBean 和setIgnoreResourceNotFound=true。

    例如:

    <bean id="myProperties" class="org.springframework.beans.factory.config.PropertiesFactoryBean">
       <property name="ignoreResourceNotFound"><value>true</value></property>
       <property name="locations">
          <list>
            <value>classpath:default.properties</value>
            <value>file:${catalina.home}/webapps/myProperties.properties</value>
          </list>
       </property>
    </bean> 
    

    注意所列文件的顺序很重要。后面文件中的属性将覆盖早期文件。

    【讨论】:

    • 请注意,该 bean 已正确定义为 &lt;property name="ignoreResourceNotFound"&gt;&lt;value&gt;true&lt;/value&gt;&lt;/property&gt;。
    • 与 intellij 的 ${catalina.home} 变量没有正确解析,有什么指针可以让它工作吗? stackoverflow.com/questions/13606328/…
    • 您可以将 util:properties 与 ignore-resource-not-found="true" 一起使用
    【解决方案2】:

    作为@ericacm 回答的后续,如果您愿意,您也可以直接在上下文中配置默认​​值,而不是使用单独的 default.properties 文件:

    <bean id="properties" class="org.springframework.beans.factory.config.PropertiesFactoryBean"
      p:location="file:${catalina.home}/webapps/myProperties.properties"
      p:ignoreResourceNotFound="true">
      <property name="properties">
         <props>
           <prop key="default1">value1</prop>
           ...
         </props>
       </property>
    </bean>
    

    注意:这里使用 p-namespace 作为 location 和 ignoreResourceNotFound 属性。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-10-31
      • 2021-01-21
      • 2010-10-16
      • 2012-03-07
      相关资源
      最近更新 更多