Access External Property File in Spring Application Context using PropertyPlaceHolderConfigurer

Target Audience: Web Component Developers, Configuration Managers and Deployment Managers

What should you know already: J2EE, Spring MVC

In an enterprise application we often use property files to share data in Java classes and XML configuration files. The problem is accessing these property files in your code. Whenever you want to read a value out of the key, you have to open stream and read the value by passing property key. This repeats every time when you want to read. Spring has excellent solution for this. The PropertyPlaceholderConfigurer brings down such complexities. Spring makes simple things simple, and complicated things possible.

Read Properties from classpath

[xml]
<bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="locations">
<value>classpath:conf/settings.properties</value>
</property>
</bean>
[/xml]

This will search the mentioned properties file in WEB-INF/classes folder.

Read Properties from external file

[xml]
<bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="locations">
<value>file:#{ systemProperties[‘user.home’]}/ur_folder/settings.properties</value>
</property>
</bean>
[/xml]

This will search the mentioned properties file in the user home directory. Here I have used SpEL ( Spring Expression Language) to get the user home directory, so that the platform independent application context loading guaranteed.

Access the property values

Say, I have the following properties saved in my home folder named xyz.properties and configured PropertyPlaceholderConfigurer in my Spring applicationContext.xml file as shown below.

The content of xyz.properties
[code]
xyz.project.name=some value
xyz.project.location=yet another value
[/code]

The bean declaration for PropertyPlaceholderConfigurer
[xml]
<bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="locations">
<value>file:#{ systemProperties[‘user.home’]}/xyz.properties</value>
</property>
</bean>
[/xml]

Now, to read the value of some key from the xyz.properties file, I could simply use as follows. Here I’m injecting my object.
[xml]
<bean id="config" class="com.myproject.ProjectConfig">
<property name="name" value="${xyz.project.name}" />
<property name="location" value="${xyz.project.location}" />
</bean>
[/xml]

Permanent link to this article: https://blog.openshell.in/2012/11/access-external-property-file-in-spring-application-context-using-propertyplaceholderconfigurer/

Leave a Reply

Your email address will not be published.