Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring properties file setting default values

I have a properties file outside my war file that is used by the system administrator to turn off certain system features. It has been working on my local machine just fine but when we deployed to a development environment the properties file was not uploaded and the application failed to startup. I was wondering if there was a way to declare default values in my applicationContext for the values that would normally come from the properties file.

I currently have this to read the properties file:

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

This works fine as long as we remember to place the properties file in the right location. Is there a way to declare default values or perhaps to read from a different file if this file is not found?

Thanks

like image 972
blong824 Avatar asked Jun 16 '11 16:06

blong824


2 Answers

Instead of using <util:properties> use a PropertiesFactoryBean with setIgnoreResourceNotFound=true.

For example:

<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> 

Note the order of the files listed is important. Properties in later files will override earlier ones.

like image 114
sourcedelica Avatar answered Sep 30 '22 14:09

sourcedelica


As a followup on @ericacm's answer, if you wish, you may also configure the defaults directly on the context instead of using a separate default.properties file:

<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>

Notes: this uses p-namespace for the location and ignoreResourceNotFound properties.

like image 37
Raman Avatar answered Sep 30 '22 12:09

Raman