Enterprise Java

Properties with Spring

1. Overview

This tutorial will show how to set up and use Properties in Spring – either via XML or Java configuration.

Before Spring 3.1, adding new properties files into Spring and using property values wasn’t as flexible and as robust as it could be. Starting with Spring 3.1, the new Environment and PropertySource abstractions simplify this process greatly.

2. Registering Properties via the XML namespace

Using XML, new properties files can be made accessible to Spring via the following namespace element:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans" 
   xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
   xmlns:context="http://www.springframework.org/schema/context"
   xsi:schemaLocation="
      http://www.springframework.org/schema/beans 
      http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
      http://www.springframework.org/schema/context 
      http://www.springframework.org/schema/context/spring-context-3.2.xsd">

      <context:property-placeholder location="classpath:foo.properties" />

</beans>

The foo.properties file should be placed under /src/main/resources so that it will be available on the classpath at runtime.

2.1. Multiple <property-placeholder>

In case multiple <property-placeholder> elements are present in the Spring context, there are a few best practices that should be followed:

  • the order attribute needs to be specified to fix the order in which these are processed by Spring
  • all property placeholders minus the last one (highest order) should have ignore-unresolvable=”true” to allow the resolution mechanism to pass to others in the context without throwing an exception

3. Registering Properties via Java Annotations

Spring 3.1 also introduces the new @PropertySource annotation, as a convenient mechanism of adding property sources to the environment. This annotation is to be used in conjunction with Java based configuration and the @Configuration annotation:

@Configuration
@PropertySource("classpath:foo.properties")
public class PropertiesWithJavaConfig {

   @Bean
   public static PropertySourcesPlaceholderConfigurer propertySourcesPlaceholderConfigurer() {
      return new PropertySourcesPlaceholderConfigurer();
   }
}

As opposed to using XML namespace element, the Java @PropertySource annotation does not automatically register a PropertySourcesPlaceholderConfigurer with Spring. Instead, the bean must be explicitly defined in the configuration to get the property resolution mechanism working. The reasoning behind this unexpected behavior is by design and documented on this issue.

4. Using Properties

Both the older PropertyPlaceholderConfigurer and the new PropertySourcesPlaceholderConfigurer added in Spring 3.1 resolve ${…} placeholders within bean definition property values and @Value annotations.

For example, to inject a property using the @Value annotation:

@Value( "${jdbc.url}" )
private String jdbcUrl;

A default value for the property can also be specified:

@Value( "${jdbc.url:aDefaultUrl}" )
private String jdbcUrl;

Using properties in Spring XML configuration:

<bean id="dataSource">
  <property name="url" value="${jdbc.url}" />
</bean>

And lastly, obtaining properties via the new Environment APIs:

@Autowired
private Environment env;
...
dataSource.setUrl(env.getProperty("jdbc.url"));

An very important caveat here is that using <property-placeholder> will not expose the properties to the Spring Environment – this means that retrieving the value like this will not work – it will return null:

env.getProperty("key.something")

4.1 Properties Search Precedence

By default, in Spring 3.1, local properties are search last, after all environment property sources, including properties files. This behavior can be overridden via the localOverride property of the PropertySourcesPlaceholderConfigurer, which can be set to true to allow local properties to override file properties.

In Spring 3.0 and before, the old PropertyPlaceholderConfigurer also attempted to look for properties both in the manually defined sources as well as in the System properties. The lookup precedence was also customizable via the systemPropertiesMode property of the configurer:

  • never – Never check system properties
  • fallback (default) – Check system properties if not resolvable in the specified properties files
  • override – Check system properties first, before trying the specified properties files. This allows system properties to override any other property source.

Finally, note that in case a property is defined in two or more files defined via @PropertySource the last definition will win and override the previous ones. This makes the exact property value hard to predict, so if overriding is important, the PropertySource API can be used instead.

5. Behind the Scenes – the Spring Configuration

5.1. Before Spring 3.1

Spring 3.1 introduced the convenient option of defining properties sources using annotations – but before that, XML Configuration was necessary for these.

The <context:property-placeholder> XML element automatically registers a new PropertyPlaceholderConfigurer bean in the Spring Context. For backwards compatibility, this is also the case in Spring 3.1 if the XSD schemas are not yet upgraded to point to the new 3.1 XSD versions.

5.2. After Spring 3.1

From Spring 3.1 onward, the XML <context:property-placeholder> will no longer register the old PropertyPlaceholderConfigurer but the newly introduced PropertySourcesPlaceholderConfigurer. This replacement class was created to be more flexible and to better interact with the newly introduced Environment and PropertySource mechanism.

For applications using Spring 3.1 or above, this should be considered the standard.

6. Configuration using Raw Beans in Spring 3.0 – the PropertyPlaceholderConfigurer

Besides the convenient methods of getting properties into Spring – annotations and the XML namespace – the property configuration bean can also be defined and registered manually. Working with the PropertyPlaceholderConfigurer gives us full control over the configuration, with the downside of being more verbose and most of the time, unnecessary.

6.1. Java configuration

@Bean
public static PropertyPlaceholderConfigurer properties(){
  PropertyPlaceholderConfigurer ppc = new PropertyPlaceholderConfigurer();
  Resource[] resources = new ClassPathResource[ ]
    { new ClassPathResource( "foo.properties" ) };
  ppc.setLocations( resources );
  ppc.setIgnoreUnresolvablePlaceholders( true );
  return ppc;
}

6.2. XML configuration

<bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
  <property name="locations">
    <list>
      <value>classpath:foo.properties</value>
    </list>
  </property>
  <property name="ignoreUnresolvablePlaceholders" value="true"/>
</bean>

7. Configuration using Raw Beans in Spring 3.1 – the PropertySourcesPlaceholderConfigurer

Similarly, in Spring 3.1, the new PropertySourcesPlaceholderConfigurer can also be configured manually:

7.1. Java configuration

@Bean
public static PropertySourcesPlaceholderConfigurer properties(){
  PropertySourcesPlaceholderConfigurer pspc =
    new PropertySourcesPlaceholderConfigurer();
  Resource[] resources = new ClassPathResource[ ]
    { new ClassPathResource( "foo.properties" ) };
  pspc.setLocations( resources );
  pspc.setIgnoreUnresolvablePlaceholders( true );
  return pspc;
}

7.2. XML configuration

<bean class="org.springframework.context.support.PropertySourcesPlaceholderConfigurer">
  <property name="location">
    <list>
      <value>classpath:foo.properties</value>
    </list>
  </property>
  <property name="ignoreUnresolvablePlaceholders" value="true"/>
</bean>

8. Conclusion

This article showed several examples of working with properties and properties files in Spring, and discussed the older Spring 3.0 options as well as the new support for properties introduced in Spring 3.1.

The implementation of all examples of registering properties files and using property values can be found in the github project – this is an Eclipse based project, so it should be easy to import and run as it is.
 

Reference: Properties with Spring from our JCG partner Eugen Paraschiv at the baeldung blog.
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

5 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
anandchakru
anandchakru
11 years ago

Nice article. Can you elaborate a little on how to do these things when different application environments (Eg: dev, prod, qa, test) ? Looking for a way to load all the properties using PropertySourcesPlaceholderConfigurer based on another value (env=dev|qa|test|prod)

Vinod Chandak
Vinod Chandak
10 years ago
Reply to  anandchakru

Use @Profile Annotation for different application environment.

e.g. @Profile(“dev”) @Profile(“prod”)

and setActiveProfile to context environment.

java2novice
10 years ago

very nice… for more java examples, visit http://java2novice.com site

Sayantan
Sayantan
10 years ago

What to do when there is multiple prop file of same key but diff values. and to be loaded in respective classes.

@PropertySource(“classpath:propA.properties”)
class A
{
fdsf();
}

@PropertySource(“classpath:propB.properties”)
class B
{
fdsf();
}

but as in applicationcontext.xml
classpath:propA.properties
classpath:propB.properties

But the issue is that it is always overloading PropB values.

How to deal with this ?

AAN
AAN
8 years ago
Reply to  Sayantan

I know it is old post. Did you get the it resolved? How?

Back to top button