Monday, January 25, 2010

JNDI InitialContext reminder

When building J2EE apps which require JNDI lookup, make sure what type of clients are instantiating the InitialContext object: should it be a container-managed class (i.e. servlet, JSF bean,etc), all you need to do is write:
try {
            Context ctx = new InitialContext();
            IHelloRemote hello = (IHelloRemote) ctx.lookup("AnotherOne/HelloBean/remote");
            hello.sayHello();
        } catch (NamingException e) {
            e.printStackTrace();
        }

But should it be just a regular POJO (btw, you CAN'T use dependency injection in EJB3 POJOs) you have to set some properties which otherwise are set by default by the J2EE app server (at least when I tried it with JBoss it worked just fine):

try{
Properties properties = new Properties(); 
                 properties.put("java.naming.factory.initial", "org.jnp.interfaces.NamingContextFactory"); 
                 properties.put("java.naming.provider.url","jnp://localhost:1099"); 
                 properties.put("java.naming.factory.url.pkgs", "org.jboss.naming:org.jnp.interfaces"); 
                  
         Context context = new InitialContext(properties);
         IHelloRemote hello = (IHelloRemote) ctx.lookup("AnotherOne/HelloBean/remote");
            hello.sayHello();
        } catch (NamingException e) {
            e.printStackTrace();
        }



Go Spring-Framework yourself...


No comments: