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
<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.
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.