Spring 3 configuration : inject .properties values into annotation driven beans

I was looking for a way to inject values of my .properties files into a annotation driven bean. I had configured a PropertyPlaceholderConfigurer but you cannot inject values of your .properties with this bean. The solution is to configure a PropertiesFactoryBean with it.

Goal

  • use the .properties file in a PropertyPlaceholderConfigurer
  • ability to inject values of this .properties file in annotation driven beans (@Controller, @Service, etc)
  • Avoid spring crashing if a .properties file is not found so we can play with .properties overriding behavior.

first, add these lines to your applicationContext.xml :


<beans:bean id="appProperties" class="org.springframework.beans.factory.config.PropertiesFactoryBean">
  <beans:property name="singleton" value="true" />
  <beans:property name="ignoreResourceNotFound" value="true" />
  <beans:property name="locations">
    <beans:list>
      <beans:value>classpath:database.properties</beans:value>
      <beans:value>file:${config.dir}/database.properties</beans:value>
    </beans:list>
  </beans:property>
</beans:bean>

<beans:bean id="propertyPlaceholderConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
  <beans:property name="properties" ref="appProperties" />
  <beans:property name="ignoreUnresolvablePlaceholders" value="true"/>
  <beans:property name="ignoreResourceNotFound" value="true"/>
</beans:bean>

  • You can see that we can put several .properties file (in the classpath or in an external folder). Here, ${config.dir} is a java environment constant passed to the JVM with the argument -Dconfig.dir=”C:/CONFIG_DIR” The external .properties file will override the classpath .properties.
  • The ignoreUnresolvablePlaceholders and ignoreResourceNotFound properties are used to avoid Spring crashing if one of the .properties file is not found

then you can inject values from your .properties in your bean classes :


@Repository
 public class MyDatabaseRepository {
 @Value("#{appProperties['database.url']}")
 private String databaseName;

@Value("#{appProperties['database.login']}")
 private String databaseLogin;

...

And in your spring XML files :


<beans:bean id="mySQLDataSource"class="org.springframework.jdbc.datasource.DriverManagerDataSource">
  <beans:property name="url">
    <beans:value>${database.url}</beans:value>
  </beans:property>
  <beans:property name="username">
    <beans:value>${database.login}</beans:value>
  </beans:property>
</beans:bean>

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>