Why do I get a NameNotFoundExcpetion when using context.lookup(“java:comp/env/MyBean”)

StackOverflow https://stackoverflow.com/questions/653966

  •  19-08-2019
  •  | 
  •  

Question

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.

Was it helpful?

Solution

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.

OTHER TIPS

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();
        } 
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top