Read property files with PropertiesFactoryBean

1. Introduction

There are scenarios where we need to externalize environment specific configurations outside the WAR. In such scenarios, we generally use PropertiesFactoryBean or PropertyPlaceholderConfigurer, though the motive of both are different.

PropertiesFactoryBean is a FactoryBean implementation which reads the property file and these properties can be used anywhere via Properties object. PropertyPlaceHolderConfigurer is a BeanFactoryPostProcessor implementation that reads the property file and uses that property file to replace placeholder variables (${somename}) with actual values in rest of the beans that get initialized though the spring context files. The read properties via PropertyPlaceHolderConfigurer are not available as a Properties object.

2. Implementation

For a simple demo, let’s create a property file user.properties at some external location with the following content –

mvc-dispatcher-servlet.xml

Note the highlighted section in the above snippet.

Now we need to inject the properties bean into the desired class. I will do it in my controller class through annotations as –


Demo.java

Update the JSP code accordingly –

hello.jsp

3. Useful Links

4. Running the application

Let’s run the above application on the server –

PropertiesFactoryBean Demo

5. Download the source code

Receive our updates to your inbox

Get more stuff like this
in your inbox

Subscribe to our mailing list and get interesting stuff and updates to your email inbox.