Tuesday, 3 November 2009

Spring Expression Langage, a simple use case.

Waiting for the release of Spring3, I have taken a look at the source code. There was an eternity that I didn’t that. My first insights where focused on the Expression Language (SpEL). When I discovered the @Value(“systemProperties[‘myProperty’]”) feature, I didn’t understand why it wasn’t more generally implemented to cover all spring managed properties those for which we used the PropertyPlaceHolderConfigurer. So I decided to make it.

It is a BeanFactoryPostProcessor that extends the PropertiesLoaderSupport the same base class as the PropertyPlaceHolderConfigurer utility. This post processor registers a bean that merges the declared properties and was exposed to the context of the SpEL which is simply the running container.

Given that properties can be accessed simply like this:


private String property;

where “properties” is simply the name of the registred bean and “property” is the name of the desired property. Note that the setter can be omitted in order to make the property immutable.

Besides, this gives me the possibility to use the EL feature to declare the locations of the properties files, to have another solution to resolve the “Complexity at the structural and dynamic level” (see this post : http://blog.springsource.com/2007/06/25/code-samples-from-springone-beyond-the-obvious-talk/).

For example I can define my files locations like this :

<bean id="spelPropertiesExposer" class="example.spring3.spel.PropertiesSpelExposer">

<property name="locationPatterns" value="configuration/%{#environment ?:'dev'}/env.properties"/>


Where “environment” is a system property wich represents the application’s environment such as dev, staging or prod. In the example if the property is undefined the default value ‘dev’ is used.

You can find the entire source code here on gitHub. And if you want to simply see the BeanPostProcessor go directly here.