Coexistence of EJB 2.1 and EJB 3 beans
EJB2 and EJB3 beans can coexist in the same enterprise application (.ear), but cannot be in the same ejb jar file (module). Therefore, EJB3 beans must be in a different jar with EJB2 beans.
Call EJB 3 from EJB 2.1
The EJB3 bean does not have a home interface, while EJB 2.1 requires it. To make an EJB3 bean available with EJB2, you need to add a local home interface (or a remote home if a remote call is required) for the EJB3 bean.
Create a home interface:
public interface SystemTimeLocalHome extends EJBLocalHome { SystemTimeLocal create() throws CreateException; }
Add a home interface to the EJB3 bean:
@Stateless @Local(TimeServiceLocal.class) @LocalHome(TimeServiceLocalHome.class) public class TimeServiceBean implements TimeServiceLocal { public long getCurrentTimeMillis() { return System.currentTimeMillis(); } }
Inside the EJB2 bean, the code for calling the EJB3 bean simply follows the EJB2 specifications: it searches for a link, calls the home interface to create a local interface, and then calls the method in the local interface.
Context ctx = new InitialContext(); TimeServiceLocalHome home = (TimeServiceLocalHome)ctx.lookup("java:comp/env/" + ejbRefName); TimeServiceLocal timeService = home.create(); timeService.getCurrentTimeMillis();
Call EJB 2.1 from EJB 3
Dependency injection is used to enter references to EJB 2.1 components in an EJB3 bean. The difference between EJB3 bean injections is that it introduces the EJB2 home interface. Call the create() method on the EJB nested home interface to instantiate the bean class.
@EJB BankingServiceHome bsHome; BankingService bs = bsHome.create(); bs.getBalance(...);
aleung
source share