Some words about JNDI

I think all Java-developers know JNDI (Java Naming and Directory Interface) and all of them use it. The common case of its use is getting datasource and getting JMS queue. In this post I’d discuss usage of JNDI for custom objects.

On one of our project we need to have access to one common knowledge base, which should be shared between several application deployed on this application server (it was glassfish v3, but it doesn’t matter).

Thus our application is based on spring framework the first idea dealt with it. We thought about implement this recommendation: http://springtips.blogspot.com/2007/06/using-shared-parent-application-context.html. But after that we found that knowledge base should work like database, but uses another API (our own). So we decided to use JNDI and implement own ObjectFactory (http://java.sun.com/javase/6/docs/api/javax/naming/spi/ObjectFactory.html).

First we created simple Data Transfer Object, which should be created by ObjectFactory and provides all necessary data to our application. It looks like:

public class Data {

private final byte[] idf;

public CkbData(final RealVector idf) {

this.idf = idf;
}

public RealVector getIdf() {

return idf;
}

}

After that we created simple implementation of ObjectFactory:

public class DataFactory implements ObjectFactory {

@Override
public Object getObjectInstance(final Object obj, final Name name, final Context nameCtx, final Hashtable environment) throws Exception {
final Reference reference = (Reference) obj;
final String property1 = (String) reference.get(“property1”).getContent();
final String property2 = (String) reference.get(“property2”).getContent();
// do something
return result;
}

}

So here name provides name of necessary resource and using obj object you may read configuration properties of this resource. After that based on these data you make create required object and return it.

By the way glassfish provides good UI for configuration custom resources – it is illustrated on the following screen:

It was very easy task and does not take a lot of time, but effect was amazing, because:

  • we have common knowledge base for all application – it significant decreased memory usage and deploying/starting time of new applications;
  • we can configure our knowledge base in runtime by changing properties of JNDI resource;
  • we should not change source of our application – we only need to change configuration files.

Therefore I suggest to take into account possibility of JNDI – it may be very useful!