≡ Menu
Spring Tutorial – PropertySourcesPlaceholderConfigurer

Spring Tutorial – PropertySourcesPlaceholderConfigurer

Spring Tutorial: How to Externalize Values from code.

In this Spring tutorial we look at how to externalize values from your Java application code ??

If this Spring Tutorial helps you and you would like the full source code and even better a free online video on this topic, so you actually watch the steps taken and follow along click here!

Remember Sharing is caring! So if you get something from this Spring tutorial please share it with others on facebookgoogle+, LinkedIn, Twitter  etc… so it may help them too! :)

It’s not seen as good practice to have actual values hard-coded into you application code.
If you deploy your application into different environments, say from development to test to live, how can those values be changed ?

Values for things like;

  • Filenames,
  • File paths,
  • Server addresses etc…
  • Usernames and Passwords.

All these and others need to be externalized from your actual Java application code. i.e. These values need to be external to your application code and pulled in at runtime from an external source. The reason is that many of the values mentioned and others may be dependent on the environment in which the application is deployed,  e.g. test or live environments. Not to mention the security concerns about having usernames and passwords hard-coded in application code.

The Spring framework helps us here and encourages us to adhere to best practices by providing a cool feature to easily solve this issue.

In this Spring tutorial, I want to take a little time to work through a simple example to show how we can configure up our Spring application to use this cool feature.

Spring provides us with a class called ‘PropertySourcesPlaceholderConfigurer’, (org.springframework.context.support.PropertySourcesPlaceholderConfigurer). It’s purpose is to support us once we have externalised our property values from being in our actual java code to being properties files.

In a previous spring tutorial I introduced Internationalization or i18n and showed how the Locale is used with a MessageSource. The locale requires language and country code values, which in the previous tutorial where left hard-coded in our application code.

In this spring tutorial, I look at how we can externalise those values into their own properties files, so they are no longer hard-coded in the application code.

Just to recap, the example was of an early morning message, where we had a British, English version;

Rise and shine Fred, this is your Sunday morning message! from Bill

and a France, French version;

Fred, Ceci est votre message de Vendredi matin! à partir de Bill

We also looked at passing in parameters of peoples name, in this case ‘Fred’ and ‘Bill’, into the message and we will look at externalizing those too.

The contents of the properties file looks like (The file itself is called live-config.properties and must be located on the classpath, I will also have a separate properties file for my tests called test-config.properties);

i18nMessageofday.language=en

i18nMessageofday.country=GB

message.name1=Fred

message.name2=Bill

 

How do we get access to a ‘PropertySourcesPlaceholderConfigurer’ ?

Well like most things in the Spring framework we start with configuration, so lets look at the XML configuration first and then look at the Spring Java Config version.

Spring XML configuration;

The first thing we need to do is to include the ‘context’ namespace in our xml configuration file. In ‘Spring Tool Suite’ (STS) IDE this is very straight forward. Open a window to edit the spring xml file and select the tab called ‘Namespaces’ then look down the list of ‘Configure Namespaces’ until you see the check box for ‘context’. Select this check box.

Once the ‘context’ namespace has been selected click on the ‘Source’ tab. You can now include the following element within your xml configuration:

<context:property-placeholder location=” ” />

(Within STS on a PC  you can use the following keys combination to get a selection of elements available,  <ctrl> + space then scroll down to “ context:property-placeholder” and select.)

Spring will automagically inject a property place holder instance into your spring application context (Spring container).

One piece of configuration is left to do… we need to tell the property place holder where to find the property file(s) ?

That’s the job of the “location” attribute, just enter the relative path for the classpath of the file(s) you need.

e.g. location=”classpath:/spring/live-config.properties

(Note: Here we prefix the path with classpath, it ensures that spring looks on our classpath for the directory ‘spring’ and properties file live-config.properties.)

Remember , within out test environment we can have a similar set-up only pointing to the properties file(s) needed for testing.

e.g. location=”classpath:/spring/test-config.properties”

Spring Java Config;

In Spring Java Config the configuration is similar but there are some subtle nuances. All the configuration is contained within Java methods in a Java class annotated with @Configuration.

Also at the class level set a @PropertySource annotation with the value of the property file location on the classpath, as in the xml example.

Finally we create a “static” method which returns the PropertySourcesPlaceholderConfigurer instance. (Note: This method must be static otherwise it interferes with other annotations when the spring application context is created!)

@Configuration

@PropertySource(value = “classpath:/spring/live-config.properties”)

@ImportResource(“/spring/live-application.xml”)

public class TestConfig {

@Bean

public static PropertySourcesPlaceholderConfigurer propertPlaceHolderConfiguer() {

return new PropertySourcesPlaceholderConfigurer();

}

}

That’s all we need for setting up the spring mechanism to manage out property values, now we need to think about how to inject the values into our Java spring application!

Step: 1

All we need to do is to ask  Spring to inject the values from the property file(s) into our Java code!

For that we can use the @Value annotation defined on an instance variable;

 

@Value(“${i18nMessageofday.language}”)

private String language;

 

@Value(“${i18nMessageofday.country}”)

private String country;

 

@Value(“${message.name1}”)

private String name1;

 

@Value(“${message.name2}”)

private String name2;

 

Ok, so the propertyPlaceHolder will look up the values from the property file, using the provided keys (e.g. i18nMessageofday.language) and inject the value into the provided instance variables

( e.g. private String name1;)

Step: 2

Now we can access and use the values placed in the instance variable like any other in Java, no more hard coded values in our application code, this is the amended getMessage() method from the previous Spring tutorial on i18n  :D

@Override

public String getMessage() {

         finalint day = GregorianCalendar.getInstance().get(Calendar.DAY_OF_WEEK);

//We access and use the instance variables like any other in Java.

      final Locale locale = new Locale(language, country);

      final String[] args = { name1, name2 };

      final String result = messageSource.getMessage(KEY_PREFIX + day, args, locale);

      return result;

}

Don’t for get to check out the Spring Tutorial on i18n!

Learn all about Core Spring with these online Spring Tutorials

Remember Sharing is caring!  If you enjoyed this Spring tutorial, help others by sharing it on facebook, google+ LinkedIn or Twitter and remember full source code is available and a free online video of this Spring tutorial, so you actually watch the steps taken and follow along click here!

Happy Coding!

Bruce

in Blog from the Den, Spring Tutorials

About the author: Bruce is a techie, a gadget geek, programmer, mentor and all round technology nut. He holds two degrees in computer science, with over 25 years in the software business. Currently working freelance as a software engineer and programming mentor. He loves what technology can do for us. Building applications using functional, Object Orientated languages & polyglot persistence helps him reconnect with the feeling of building something tangible. To learn more about Bruce, follow him on Twitter @denofprogram

{ 0 comments… add one }

Leave a Comment