Problem solve Get help with specific problems with your technologies, process and projects.

Typecasting the remote interface of EJB

When will I typecast my remote interface of EJB to EJBHome (Remote Home) and when will I typecast it to a Local EJB Home?
Prior to EJB 2.0, the only one way to obtain a reference to an EJB, no matter where the EJB was located, was to execute a lookup for the EJB's remote interface. This produced a lot of unnecessary overhead when accessing the EJB within the same JVM, such as the case when one EJB accesses another EJB.

With the release of version 2.0 of the EJB specification, the local interface was introduced to eliminate the network overhead incurred when accessing an EJB in the same JVM. An EJB can be defined as implementing a local interface, a remote interface, or both.

The primary differences between local and remote EJBs are:

1) The home interface for a local EJB must extend javax.ejb.EJBLocalHome and the home interface for a remote EJB must extend javax.ejb.EJBHome.

2) The bean interface for a local EJB must extend javax.ejb.EJBLocalObject and the bean interface for a remote EJB must extend javax.ejb.EJBObject.

3) The lookup mechanism for a remote EJB includes:
a) Properties passed to the InitialContext constructor
b) Requirement to narrow the home object

The lookup steps are compared in the following examples:

Local interface lookup steps:

InitialContext jndiContext = new InitialContext();
MyEJBLocalHome home =
Remote interface lookup steps:
Properties props = new Properties();
props.put(Context.SECURITY_PRINCIPAL, "jdoe");
props.put(Context.SECURITY_CREDENTIALS, "foobar");
props.put(Context.PROVIDER_URL, "some://provider.url");
InitialContext jndiContext = new InitialContext(props);
Object objref = jndiContext.lookup("java:comp/env/ejb/MyEJB");
MyEJBHome obj =
Good application frameworks will usually hide the lookup differences between local and remote EJBs in a factory object and expose similar methods for both, as follows:
public EJBLocalHome lookupLocalEJB(String jndiHomeName)

public EJBHome lookupRemoteEJB(String jndiHomeName)
Your decision to cast to a local interface or a remote interface can now be made in a clean manner within these separate methods.

Dig Deeper on Topics Archive

Start the conversation

Send me notifications when other members comment.

Please create a username to comment.