Read Properties File in Spring Xml using PropertyPlaceholderConfigurer

The Read Properties File in Spring Xml tutorial show you how to load properties from a file using spring property placeholder. In Spring, we can use PropertyPlaceholderConfigurer to parameterize property values from a bean definition in a separate file. This helps developer organize specific properties in a external file instead of having to hard code values in the application. PropertyPlaceholderConfigurer also support to load multi property files, this allows developer can divide and store property values into different file with different purposes.

Here, we have two property files and store in classpath.

application.properties file

jdbc.properties

Create simple POJO

Here is a simple POJO where we are going to load the properties to .

Read Properties File in Spring XML using Property Placeholder

To read properties from file application.properties and jdbc.properties we must configure spring xml file like below

Let’s dig deeper:

The element indicate property filenames and their location with spring container. Default location is often stored in classpath directory. You can declare multi property files and they are separated by commas.

This configuration declares a bean and set the loaded properties through setter injection.

The above configuration uses the expression language (el) notation ${property.name} and it is often called “key”. At runtime, the key is replaced with the corresponding value from the property file that is declared in Spring xml configuration file. If the key doesn’t exist, an exception is thrown at startup

Similary, we can inject value from jdbc properties for dataSource bean like below

Testing the read properties file
We create a main class to get a User bean that is assigned the loaded properties through setter injection. And save this bean in database using data source

Run the main above and see output like below

That’s all on the tutorial Read Properties File in Spring Xml using PropertyPlaceholderConfigurer

Leave a Comment

*

Please share it if you found this useful
Hide Buttons