Resolving Variables from a Property File in Spring

When writing the configuration in a Spring file, sometimes it is desirable to maintain a list of properties external to the Spring configuration. This list of properties can be edited and the updated values will be picked up by the Spring configuration. This tech-recipe will show you how it is done.

1.In your Spring enabled Java project, create a properties file in the src/main/resources folder by right-clicking the src/main/resources folder and choosing New > File. This file can be named anything as long as it corresponds with the name you will define in your Spring configuration file. For this tech-recipe we will name it project.properties.

2.In the project.properties file, a new property is defined with the name on the left and value on the right separated by an equal sign (=) as seen in the example below (beanType=String). We can then use this property in our Spring configuration file.

3.Now, it is necessary to open your Spring application-context.xml in order to add the configuration code which will load the values from the property file. This is configured with the Spring PropertyPlaceholderConfigurer class. Notice that the project.properties from Step 2 is defined in the property locations list. Also, notice the placeholder prefix. This will be explained in Step 4.

4.In the application-context.xml file, we will create a simple bean definition which will use the value from the project.properties file. We will create a bean named projectBean and have its type vary depending on the value from the project.properties file. Notice that the property must be resolved between the ${} construct. This is due to the placeholder prefix we defined in Step 3. The resolved value will ensure that the bean’s class is java.lang.String, with the String portion resolving from the properties file.

You may now dynamically configure properties for your Spring project. The projectBean could be dynamically changed to have type java.lang.Object with a simple update of the project.properties file.

 

About Alex Bahdanovich

Writer, author, wordsmith -- this tech enthusiast enjoys Starbucks, good reads, and golden retrievers.
View more articles by Alex Bahdanovich

The Conversation

Follow the reactions below and share your own thoughts.

Leave a Reply