Spring Bean Configure XML Accessing Context.xml JNDI Resources

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


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.


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

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

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"
<bean id="myPasswordBean" class="org.springframework.jndi.JndiObjectFactoryBean">
	<property name="jndiName" value="java:comp/env/myPassword"/>

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.

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 )

Google photo

You are commenting using your Google 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 )

Connecting to %s