Java Reference
In-Depth Information
5-3. Accessing EJB 2.x Components in Spring
Problem
In EJB 2.x, you have to perform the following tasks to invoke a method on a remote EJB component.
Invoking a method on a local EJB component is very similar, except that you have no need to handle
RemoteException .
Initialize the JNDI lookup context, which may throw a NamingException .
Look up the home interface from JNDI, which may throw a NamingException .
Retrieve a remote EJB reference from the home interface, which may throw a
CreateException or a RemoteException .
Invoke the method on the remote interface, which may throw a RemoteException .
As you can see, it requires a lot of coding to invoke a method on an EJB component. The exceptions
NamingException , CreateException , and RemoteException are all checked exceptions that you must
handle. Moreover, your client is bound to EJB and would require a lot of changes if you ever switched the
service implementation from EJB to another technology.
Solution
Spring offers two factory beans, SimpleRemoteStatelessSessionProxyFactoryBean and
LocalStatelessSessionProxyFactoryBean , for creating a proxy for a remote/local stateless session
bean respectively. They allow EJB clients to invoke an EJB component by the business interface as
if it were a simple local object. The proxy handles the JNDI context initialization, home interface
lookup, and invocation of local/remote EJB methods behind the scenes.
The EJB proxy also converts exceptions such as NamingException , CreateException , and
RemoteException into runtime exceptions, so the client code is not required to handle them. For
example, if a RemoteException is thrown when accessing a remote EJB component, the EJB proxy
will convert it into Spring's runtime exception RemoteAccessException .
How It Works
Suppose that there's a front desk subsystem in your post office system that requires postage calculation.
First, let's define the FrontDesk interface as follows:
package com.apress.springenterpriserecipes.post;
public interface FrontDesk {
public double calculatePostage(String country, double weight);
}
 
Search WWH ::




Custom Search