27/01/2009

How To Export Spring Managed Bean To JNDI

Sometimes, it is necessary to export a spring managed bean to JNDI context. Here I want to show how do it.

In spring, there is a bean that provides a similar functionality for exporting to MBean server: MBeanExporter. Unfortunately, there is no standard JNDI bean exporter implementation in spring (current version is 2.5.6) - (Why?).
But it's easy to write it youself:
package com.example.spring.jndi.export;

import org.springframework.beans.factory.DisposableBean;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.jndi.JndiTemplate;

public class JndiExporter implements InitializingBean, DisposableBean {

private String jndiName;

private Object bean;

private final JndiTemplate jndiTemplate = new JndiTemplate();

public String getJndiName() {
return jndiName;
}

public void setJndiName(String jndiName) {

this.jndiName = jndiName;
}

public Object getBean() {
return bean;
}

public void setBean(Object bean) {
this.bean = bean;
}


public void afterPropertiesSet() throws Exception {
jndiTemplate.bind(jndiName, bean);
}

public void destroy() throws Exception {
if (bean != null && jndiName != null && bean == jndiTemplate.lookup(jndiName)) {
jndiTemplate.unbind(jndiName);
}
}
}

Add following fragment to spring configuration file:
<bean id="myBean" class="com.example.MyBean"/>

<bean class="com.example.spring.jndi.export.JndiExporter">
<property name="bean" ref="myBean" />
<property name="jndiName" value="MyJNDIName"/>
</bean>
Don't forget to make your bean serializable by implementing java.io.Serializable interface.
Now we can lookup exported bean by adding to the spring config fil:
<jee:jndi-lookup id="myJndiBean" jndi-name="MyJNDIName" proxy-interface="com.example.IMyBean" lookup-on-startup="false"/>

That's all, folks!

2 comments:

  1. Hi
    I am trying to export a XA connection factory that my Sessionfactory needs for Hibernate Search. I have used your example but the problem is that the exporter bean isn't initialised before the session factory is constructed.

    I don't want to make the sessionfactory depend on the exporter (using the depends-on tag). Not sure what approach to take. I could use the app context started event but that would mean that my xa connection factory bean may not have been initialised.

    Any help would be appreciated.

    ReplyDelete
  2. Hi, Aminmc.

    You need the Exporter to be initialized before SessionFactory will try to access JNDI. You will not be able to get your bean (connection factory) from JNDI until Exporter place it there.

    You may try to load you SessionFactory lazily by setting lazy-init="true".
    You may also try to set lazy-init="false" for Exporter to ensure that the Exporter will be loaded before SessionFactory.

    Good luck :-)

    ReplyDelete

redirect