Read properties files in Spring using context namespace

In this tutorial, I will show you how to read file properties in Spring using the context namespace.

But first, let’s create an example project.

Read properties files in Spring using context namespace

I will use Java 17 for this example:

Spring framework dependency:

Class Application:

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

spring.xml

configuration.properties

Now, I will be configuring the context namespace in Spring’s configuration file so that it can read the properties in the configuration.properties file, and then our application can use it!


First, you need to declare using the context namespace as an attribute of the <beans> tag:

Now, we use the context namespace to read the properties file:

In this declaration, I used a <context:property-placeholder> tag of the context namespace to declare the path of the properties file.

If the path of the properties file does not exist, when running the application, we will encounter an error immediately. For now, let’s edit the path of the properties file as follows:

When running you will encounter the following error:

To ignore this error, you can declare another attribute for the <context:propery-holder> tag as follows:

Then, Spring only displays a message telling us there is a non-existent property file as follows:

To read multiple properties files at the same time, you also use the location attribute of the <context: property-holder> tag and the path of the properties files will be separated by a comma.

For example, if I add a database.properties file in my example, I will declare the context namespace as follows:

2/5 - (1 vote)

Add Comment