tags:

views:

607

answers:

2

Why do I get a NameNotFoundException when using context.lookup("java:comp/env/MyBean") but not when I use context.lookup(MyBean.class.getName()) ?

The error reports "No object bound for java:comp/env/MyBean" How do I bind the name and why does class.getName() still work? Why would I use java:comp/env ?

I'm using Netbeans 6.5, Glassfish 2.1.

A: 

The java:comp/env prefix is used for something called a resource reference. It is an abstraction between the resource you are looking up and the actual JNDI name of the resource. It allows you to change the location of the underlying resource (i.e. different server and context) without affecting your lookup code.

I have only used it in WAS, but the idea is that you create a reference to an existing resource (JMS, JDBC, EJB ...) for each module that needs to access the resource. It is part of your deployment configuration.

Tutorial from Sun here and Glassfish example here.

Robin
Thanks. If the server and context changes, wouldn't class.getName() still work? I guess the class name could change and I could then map some other class to my lookup code using java:comp/env
Bedwyr Humphreys
I can only assume that the JNDI name in your case matches your fully qualified bean name. I have never seen that done before. The problem is when the bean is not deployed locally, so your default InitialContext will not be able to find it.
Robin
If the bean is deployed in a different server, the JNDI for lookup would be fully qualified, for example "corbaname:iiop:someHost:2809#com/mycompany/accounting/MyBean". Using a reference would only change the deployment descriptor and you would not have to code this godawful string.
Robin
A: 

I am not sure if this is true for Glassfish or not, but in case of JBOSS, if you turn on DEBUG, you can notice the jndi name that would be used.

For example, during the deployment of a session bean named DemoBean, you will see the following log in the server.log file:-

2009-07-24 09:08:18,747 DEBUG [org.jboss.ejb3.stateless.StatelessDelegateWrapper] Creating jboss.j2ee:jar=SessionBeanDemo.jar,name=DemoBean,service=EJB3 2009-07-24 09:08:18,747 DEBUG [org.jboss.ejb3.ProxyDeployer] no declared remote bindings for : DemoBean 2009-07-24 09:08:18,747 DEBUG [org.jboss.ejb3.ProxyDeployer] there is remote interfaces for DemoBean 2009-07-24 09:08:18,747 DEBUG [org.jboss.ejb3.ProxyDeployer] default remote binding has jndiName of DemoBean/remote

Then in your client code you can look it up like this:-

        InitialContext ctx;
     try {
      ctx = new InitialContext();
      DemoBeanRemote demo = (DemoBeanRemote) ctx.lookup("DemoBean/remote");
         System.out.println(demo.sayHello());
     } catch (NamingException e) {
      e.printStackTrace();
     }