Friday, March 26, 2010

I was playing around with Spring 3.0 and the new Spring Expression Language SpEL the last couple of days and ran across a few issues. First the Spring documentation is a little lacking in this area so I am going to share what I have found.

The problem that I was working to solve was that we store our properties files outside of the War file and use a context property to point to the directory where the file is located. In Spring 2.5.6 this was a little complicated but with Spring 3.x it’s much easier when you use SpEL.

With SpEL you can access several types of properties right out of the box. Here is a list of the ones that I know about. (systemProperties, systemEnvironment, contextAttributes, contextParameters)

The key one for my use was finding the contextParameters. What I do is to setup a parameter name in my context xml file for Tomcat.

<Context className="org.apache.catalina.core.StandardContext" cachingAllowed="true"
charsetMapperClass="org.apache.catalina.util.CharsetMapper" cookies="true" crossContext="true" debug="0"
docBase="C:\Data\etc\eclipse\projectName1\web" mapperClass="org.apache.catalina.core.StandardContextMapper"
path="/projectName1" privileged="false" reloadable="false" swallowOutput="false" useNaming="true"
workDir="work\Standalone\localhost\projectName1" wrapperClass="org.apache.catalina.core.StandardWrapper">
<Parameter name="config.home" override="true" value="C:\Data\etc\eclipse\projectName1\properties"/>
</Context>

Now in my application context xml file I can access this parameter with the SpEL command.

#{contextParameters['config.home']}

So to load up my application’s properties file it’s as easy as using the property loader like this…


<util:properties id="appProperties" location="file:#{contextParameters['config.home']}/myApplication.properties">
</util:properties>

Now the properties can be used anywhere in your application as necessary. This seems fairly simple but I searched the web and the latest Spring docs without success to find this information. I dug into the Spring source last night to location exactly what I needed to make this work like I wanted. I hope that this helps someone else and yes I’m going to put in a Jira to get the Spring docs updated to include the values list above.
Brian