Read properties files in Spring using PropertyPlaceholderConfigurer object

Spring provides us with several ways to read our application’s configuration files: properties files. In this tutorial, I will tell you the most common way is to use the PropertyPlaceholderConfigurer object.

First, I will create a Maven project as an example:

Read properties files in Spring using PropertyPlaceholderConfigurer object

With the Application class has content as follows:

I will use Java 17 for this example:

Spring framework dependency:

In our project, the spring.xml file is Spring’s configuration file and the configuration.properties file is the configuration file of the application. The contents of these files are as follows:

spring.xml

configuration.properties

Now we will use the PropertyPlaceholderConfigurer object to read the properties found in the configuration.properties file above for our application to use!



Simply put, we can declare the PropertyPlaceholderConfigurer object in Spring’s configuration file as follows:

With this declaration, Spring will use the path as the value of the property location to search for the properties file and to read all the properties contained in this file. In my above declaration, I used the classpath variable, which corresponds to the /src/ main/resources path, and then the file name.

At the start of the application, if Spring cannot find the properties file we have declared, it will report the error immediately. For example, now I have renamed the configuration.properties file to configuration1.properties, it will say something like this:

To ignore this error, you would declare to add another property ignoreResourceNotFound to the PropertyPlaceholderConfigurer object as follows:

In case your application has multiple configuration files, to read all the properties in those configuration files, you must use the locations attribute of the PropertyPlaceholderConfigurer object. For example, I create a new database.properties file:

Read properties files in Spring using PropertyPlaceholderConfigurer object

to contain information related to the database connection for the application with the following content:

To read this database information, you must modify the declaration for the PropertyPlaceholderConfigurer object as follows:

Add Comment