Spring Bean Configure XML Accessing Context.xml JNDI Resources

Tomcat context.xml can expose environment variables accessible by Spring bean configuration xml files.

Problem:

Sometimes you want to externalize some application properties, such as password or QA/Production specific settings, used by Spring beans. There are a few options for doing so and this post focuses mainly on Tomcat based web application by putting the properties in its context.xml file.

Solution:

Step#1: Put the properties into context.xml as environment entities

<Context>
  <Environment name="myPassword" value="xxx" type="java.lang.String" override="false"/>
</Context>

This essentially exposes the properties to JNDI java.comp/env context.

Step#2: Access them from Spring bean config file

<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:lang="http://www.springframework.org/schema/lang"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/lang
http://www.springframework.org/schema/lang/spring-lang-3.0.xsd">  
<bean id="myPasswordBean" class="org.springframework.jndi.JndiObjectFactoryBean">
	<property name="jndiName" value="java:comp/env/myPassword"/>
</bean>
</beans>

Now you get a reference of myPassword defined in the context.xml.

Other Solutions:
There are a few other ways to externalize the bean properties without Tomcat, such as passing them in from JVM arguments or in a separated properties files using PropertyPlaceholderConfigurer. They are not covered by this post.

Advertisements
This entry was posted in Java and tagged , , , , , , . Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s