Read property files with PropertyPlaceholderConfigurer

1. Introduction

Usually when we are concerned with multiple servers where the application is deployed before going into production, we can configure the environment-specific parameters in an external property file. It might be the database details, which is different for test server and the production server. So it’s better we we choose to keep the database configuration file in an external property file. Similarly, we can choose to keep LDAP server details in an external property file. With property files in place, we don’t need to touch the configuration XML files, where the property file values can be directly picked up as ${name}.

All we need to do is to update the property file accordingly at every deployment, without even touching the Spring configuration context files.

In this tutorial, we will see how we can make use of PropertyPlaceholderConfigurer to read external property file values and access them from bean configuration in Spring.

2. Implementation

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

With that in place, lets make sure we have the application context file content as –


applicationContext.xml

Note the highlighted section in the above snippet.

We have the main class below, which we will try to run.

MainApp.java

3. Useful Links

4. Running the application

Running the above as java application displays as –PropertyPlaceholderConfigurer 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.