For your bean to call another bean, you must go through the same process that
any other client would go through. Your bean might:
1. Look up the other bean’s home object via JNDI
2. Call create() on the home object
3. Call business methods on the EJB object
4. Call remove() on the EJB object
As we learned about earlier, to lookup a home via JNDI, you first need to supply
JNDI initialization parameters, such as the JNDI driver you’re using, which
differs from container to container. But if you’re writing a bean that calls
another bean, how do you know what JNDI service provider to use? After all,
your beans should be container-independent. Hard-coding that JNDI information
into your bean would destroy portability.
The good news is that if you’re looking up a bean from another bean, you
don’t need to supply any JNDI initialization parameters. You simply acquire a
default JNDI initial context. The container sets the default JNDI initial context
before your bean ever runs. For example, the following code snippet is taken
from a bean calling another bean:
// Obtain the DEFAULT JNDI initial context by calling the
// no-argument constructor
Context ctx = new InitialContext();
// Look up the home interface
Object result = ctx.lookup("java:comp/env/ejb/CatalogHome");
// Convert the result to the proper type, RMI-IIOP style
CatalogHome home = (CatalogHome)
javax.rmi.PortableRemoteObject.narrow(
result, CatalogHome.class);
// Create a bean
Catalog c = home.create(...);
The preceding code is portable because nobody ever needs to supply
container-specific JNDI initialization parameters.