Monday, March 8, 2010

Spring and JNDI

You can inject a jndi object to Spring bean as follows: In your server.xml file configure objects to be registered in JNDI (sample is for tomcat server) as follows:

<context source="org.eclipse.jst.jee.server:Sample" reloadable="true" path="/Sample" docbase="Sample"> <resource factory="org.apache.naming.factory.BeanFactory" auth="Container" type="com.test.SampleBean" name="services/SampleBean"> </context>

The resource tag within the context tag registers the bean in JNDI. Now, to inject the JNDI object into a Spring bean during bean initialization, do the following in you spring.xml bean configuration

<bean class="org.springframework.jndi.JndiObjectFactoryBean" id="SampleBeanWithJNDIInjection"><property name="jndiName"><value>java:comp/env/services/SampleBean</value></property><property name="resourceRef" value="true"></property> </bean>

The above configuration, loads the bean available in the JNDI directory into the new Spring Bean