Search code examples
javaspringconfigurationjndi

how to put(bind) object to jndi in spring declaratively?


We have a plain standalone spring application and we need to put jdbc datasource in jndi. (we use jboss treecache and it need datasource to be in the jndi).

Some googling found most of all jndi-lookup examples with spring, where an object is already put in jndi (by tomcat or application server etc), but we need otherwise: I have a plain datasource Spring bean, which I inject to other services, but I can't inject it to TreeCache, because it needs it only from jndi.

Found org.springframework.jndi.JndiTemplate, which can be declared as bean, e.g.:

<bean id="fsJndiTemplate" class="org.springframework.jndi.JndiTemplate">
    <property name="environment">
        <props>
            <prop key="java.naming.factory.initial">com.sun.jndi.fscontext.RefFSContextFactory</prop>
            <prop key="java.naming.provider.url">file:///c:\windows\temp</prop>
        </props>
    </property>
</bean>

but not found how to bind with it other than in java code: fsJndiTemplate.bind(name, obj) from init-method of some other bean. Is there any way to do it declaratively?


Solution

  • Your can create a JndiExporter which uses a JndiTemplate to bind a map of object with a name:

    <bean id="jndiExporter" class="org.xxx.JndiExporter">
        <property name="jndiTemplate" ref="jndiTemplate">
        <property name="objects">
              <map>
                <entry key="name1" value="bean1"/>
                <entry key="name2" value="bean2"/>
                <entry key="name3" value="bean3"/>
                <entry key="name4" value="bean4"/>
              </map>
        </property>
    </bean>
    

    Your JndiExporter have to implements BeanFactoryAware to retrieve the spring bean with the injected BeanFactory.

    This is one possible may :)