Using more than one property file in Spring MVC

Spring is one of the most important, powerful and also complex frameworks in the actual Java panorama.

Unfortunately for me, I’m very forgetful so it is worth to write a post-reminder to increment the possibilities I never forget again something like this.

Using property files in Spring

Since Spring 3, the use of properties in our code was made really simple thanks to the placeholders.

Supposing a property file my_config_1.properties with next content:

It is enough to add the next configuration element in our servlet configuration XML file:

Later, at any place of our program we can easily get the properties using @Value annotation:

And what if you have more than one property files?

Supposing we have a second property file my_config_2.properties with the values:

Spring allows to specify more than one properties file adding a new placeholder:

The problem comes when you try to use the property from the second file, using @Value("${second_file_prop}"), Spring will throw an exception saying it can find the second_file_prop value. This is because Spring try to find the property in the first file and if it does not find it throws an error.

To avoid this ugly effect we need to use the ignore-unresolvable attribute in the placeholder:

This way if Spring does not find a property in the first file it will continue looking at the second one.

The order

In addition, the placeholder element can use the order attribute that determines the order in which Spring must look at the files. So a good way to express the previous configuration is:

2 Responses

  1. Sammer December 17, 2013 / 13:31

    In you last example with the order attributes, I noticed that the ignore-unresolvable attribute is set on both elements. So what happens if I try to fetch a value @Value(“${non-existing-prop}”) that is not defined in any of the property files in that example? Do I still get the exception once Spring runs out of property files to check?
    Thanks in advance for the answer. :)

    • asantiago December 17, 2013 / 21:20

      Yes, you will receive an exception if properties doesn’t exist.

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code class="" title="" data-url=""> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre class="" title="" data-url=""> <span class="" title="" data-url="">