Using properties in Spring configuration file

In some previous tutorials, I already introduced with you all about how to read properties files in Spring using PropertyPlaceholderConfigure object, namespace util, or namespace context. So, how we can use these properties in the Spring configuration file? In this tutorial, I will guide you all about that.

First of all, I will create a new Maven project for example:

Using properties in Spring configuration file

I will use Java 17 for this example:

Spring framework dependency:

HelloWorld class:

  • Application class:

  • configuration.properties

  • spring.xml

Here, I used namespace context to read the configuration.properties.

To use these properties in the Spring configuration file, we need to declare them with the following syntax:

With this declaration, Spring will ingest the value of the property into beans in the Spring configuration file automatically.

For example, I will declare the HelloWorld object as a bean in the Spring configuration file with the value of the name attribute as the value of the name property in configuration.properties, as below:

Result:

Using properties in Spring configuration file

Note, if a property was declared in multiple properties file then the value of this property will be in the last declaration properties file.

For example, I add more properties file, named configuration-override.properties

Using properties in Spring configuration filewith the following content:

and declare using this property in namespace context:

then when running, the result is as below:

Using properties in Spring configuration file

Add Comment