Working with multiple properties files in Spring Framework

In this short tutorial, let’s go through how to work with multiple properties files in Spring framework.

It’s always better to have properties in multiple files grouped by usage/category. In this example, we have 2 files,

  • database.properties – containing database related properties
  • email.properties – containing email related properties

In PropertyPlaceholderConfigurer bean definition, we’re using placeHolderPrefix property to define the prefix of the properties to be looked up in given properties file.

For example, if any bean needs a configuration “database.driver.name”, spring will look for “driver.name” property in database.properties file as it knows the prefix for all the properties in database.properties is “database.”.

spring-config.xml


<bean id="dbProperties" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
        <property name="placeHolderPrefix" value="${database." />
        <property name="location" value="classpath:database.properties" />
        <property name="ignoreUnresolvablePlaceHolders" value="false" />
        <property name="ignoreResourceNotFound" value="false" />
    </bean>

    <bean id="emailProperties" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
        <property name="placeHolderPrefix" value="${email." />
        <property name="location" value="classpath:email.properties" />
        <property name="ignoreUnresolvablePlaceHolders" value="false" />
        <property name="ignoreResourceNotFound" value="false" />
    </bean>

database.properties

driver.name=somedriver
show.sql=true

email.properties

smtp.name=someName
from.address=someAddress

As the default value for ignoreUnresolvablePlaceHolders is false, if our application has multiple properties files, spring will try to resolve all properties in a particular file and throws exceptions if it can’t find certain properties.

By using placeHolderPrefix, spring will try to resolve only the properties with certain prefix in a particular file and doesn’t throw exception if it finds the properties.

Advertisements
This entry was posted in java and tagged , , , , , , , . Bookmark the permalink.

2 Responses to Working with multiple properties files in Spring Framework

  1. Pingback: Spring Data REST Java Configuration Example | iDoDevJobs

  2. Pingback: Develop a simple RESTful Webservices using Apache CXF and Spring Framework – Part I | iDoDevJobs

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s