Client View of Bean  «Prev 

JNDI initialContext() Lookup

How to Use JNDI to Locate Home Objects

To achieve location transparency, EJB containers mask the specific locations of home objects from your enterprise beans' client code. Clients do not hard-code the machine names that home objects reside on, rather, they use JNDI to lookup home objects.
Home objects are physically located somewhere on the network or perhaps in the address space of an EJB container residing on machine #1, or perhaps on a container residing on machine #2. As a developer who writes client code to use beans, you do not care.
For clients to locate a home object, you must provide an alias for your bean's home object. Clients will use this alias to identify the home object it wants. For example, our Hello World example might have an alias HelloHome. You specify this alias using the proprietary vendor-specific files that are bundled with your bean. When you deploy your bean into the container, the container automatically binds the alias HelloHome to the home object. Then any client on any machine across a multitier deployment can use that alias to find home objects, without regard to physical machine locations.
Clients use the JNDI API to do this. JNDI goes over the network to some naming service, or JNDI tree, to look for the home object, perhaps contacting one or more naming services in the process. Eventually the home object is found, and a reference to it is returned to the client.

Figure 4.4 Acquiring a reference to a home object.
Figure 4.4 Acquiring a reference to a home object.

EJB Context Lookup
EJB Context Lookup

javax.naming.Context initialContext = new javax.naming.InitialContext();

The JNDI initialContext() method returns the initial context. The initial context is equivalent to the root directory of the JNDI Name Service. The result is stored in the variable initialContext.
Object objRef = initialContext.lookup("MyHello")

Looks up the "MyHello" service in the initial context and returns the remote reference (the stub) for the Hello bean's home object.
This reference is stored in objRef.
javax.rmi.PortableRemoteObject.narrow(
Transforms the actual remote reference type, stored in objRef, to a HelloHome reference.
HelloHome home
home will contain the remote reference (the stub) to the home object when the statement is completed.
The stub implements the HelloHome interface.
(HelloHome)
A Java cast to the correct type.
HelloHome.class
The class of the return from lookup. This is required by the narrow()method.