Read properties file in Spring using util namespace

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

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

Read properties file in Spring using util namespace

The contents of the Application class are as follows:

I will use Java 17 for this example:

Spring dependency:

In my 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 configure the util namespace in Spring’s configuration file so that it can read the properties contained in the configuration.properties file for our application to use.


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

Next, you will use the util namespace to read the properties files as follows:

In the above declaration, I used the <util:properties> tag to declare the path of the properties file.

The special with the util namespace is that with the above declaration, properties are read into an object of the java.util.Properties class with a variable named id, in my example it is the properties variable. When using properties with util namespace, the usage is also easier.

You can check this by adding some lines of code to the Application class as follows:

then the results will be:

Read properties file in Spring using util namespace

The util namespace also supports our ignore-resource-not-found attribute so that our application does not have an exception when the path of the properties file does not exist.

Declare as follows:

Add Comment