Properties in Spring

Daniel Díaz Carrete
2 min readJan 7, 2018

I’m writing this to help me sort out the different ways of handling properties in Spring.

Using a PropertiesFactoryBean

This is perhaps the simplest way. You can declare a bean of this type using the bean configuration element or the more convenient util:properties element, and then inject it as a Properties object.

Besides the usual .properties format, you can also put the properties in a xml file, which can be more convenient for complex multi-line properties.

Using Environment and PropertySource

Modern versions of Spring provide Environment, a centralized store of all properties, environment variables and system settings for the running application. Environment is also aware of profiles. You can inject the Environment into your own objects in the usual way.

When using Java-based configuration, you can add properties to the Environment using the PropertySource annotation. There doesn’t seem to be (?) a comparable xml configuration element that does what PropertySource does.

Substituting references to properties in configuration files

We might want to replace references to properties in our xml configuration files, or in the arguments to the Value annotation.

You can do this by registering one or more PropertySourcesPlaceholderConfigurers in your xml configuration using the property-placeholder element.

PropertySourcesPlaceholderConfigurer resolves references to its own local properties, and is Environment-aware as well, so it also resolves references to properties available in the central Environment. It does not, however, put its own local properties in the Environment.

There is an earlier (obsolete?) version of the class, named PropertyPlaceholderConfigurer, that doesn’t resolve references to properties in the Environment. In old versions of Spring , the property-placeholder element registered PropertyPlaceholderConfigurers, but now it registers PropertySourcesPlaceholderConfigurers.

There is a subtlety to keep in mind: appliation contexts can be in a parent-child relationship, and resolution of references to properties is only performed for the context in which the placeholder configurer was registered.

(Note: It seems that you can also resolve references to specific Properties beans or to system properties by using Spring EL, but this feels less elegant.)

Which method to use?

The javadocs for the Environment class say the following:

application-level beans should not need to interact with the Environment directly but instead may have to have ${…} property values replaced by a property placeholder configurer such as PropertySourcesPlaceholderConfigurer, which itself is EnvironmentAware and as of Spring 3.1 is registered by default when using <context:property-placeholder/>

I suppose the reason for this advice is that using Environment couples your bean to a Spring-specific API, which should be avoided when less invasive alternatives exist.

--

--