Standalone JNDI

I have a need at work to implement a standalone command line Java program that needs to be able to use local JNDI.  I’ve got it working, but it was way harder to figure out than it should have been, and I couldn’t find any blog postings that used the version of code that I used.  So, I’m documenting here.

If you don’t already know what any of this means, move along, nothing to see here.

I’m using the JBoss JNDI provider, which is in the default JBoss distribution.  I’m using JBoss 4.2.2.GA

First, add the jars you need to your classpath:

  • jnpserver.jar
  • jbossall-client.jar

Next, write a jndi.properties file with these entries:

java.naming.factory.initial=org.jnp.interfaces.NamingContextFactory
java.naming.factory.url.pkgs=org.jboss.naming

Make sure the jndi.properties file is on your classpath.

Then, include this in your code.  I suggest at the top of your main(), where it gets run at start:

try {
 NamingBeanImpl jnpServer = new NamingBeanImpl();
 jnpServer.start();

 } catch (Exception e) {
 // TODO Auto-generated catch block
 e.printStackTrace();
 }

That’s it, you now have JNDI available in your program.  There is probably more that can be done with the jndi.properties file to load objects at start, but I’ll learn that as I need it.

To add things to the context programmatically:

 Object object = "TestApp";
 String name = "config.appName";
 Context context = new InitialContext();
 context.bind(name, object);

To look up an object in the context:

 Context context = new InitialContext();
 Object object = context.lookup(name);