22 June 2011

JNDI in POJO

If you have used JNDI lookup in your services, JSPs or servlets, it was as easy as looking it up using some code like this:

InitialContext ctx;
ctx = new InitialContext();
MyBean hello = (MyBean) ctx.lookup("MyBean");


However, if you want to use this code in a POJO style, you won't be successful, looking up that JNDI. In the first cases, you were running your code within a container, thus you don't need any specific configuration and the container will take care of it. However, in a POJO style (i.e. using main() method), you need to have some specification detailed out. One need to set up server properties to get the InitialContext.

For JBoss, you need to have the following set and be passed to your InitialContext:

Hashtable env = new Hashtable();
env.put(Context.INITIAL_CONTEXT_FACTORY, "org.jnp.interfaces.NamingContextFactory");
env.put(Context.PROVIDER_URL, "localhost:1099");
env.put(Context.URL_PKG_PREFIXES, "org.jboss.naming.client");
Context ctx = new InitialContext(env);


You also can create a jndi.properties files with the following parameters, and place them in your class-path.

java.naming.factory.initial=org.jnp.interfaces.NamingContextFactory
java.naming.provider.url=jnp://localhost:1099
java.naming.factory.url.pkgs=org.jboss.naming:org.jnp.interfaces

Resources:

http://community.jboss.org/wiki/AccessEJBsRemotely

No comments:

Post a Comment