Thursday, July 10, 2008

Using dependency injection in EJB2

Many J2EE developers are still facing legacy projects, often containing horrible EJB2 session beans. Once I understood the improvements of EJB3 and the Spring alternatives for dependency injection, I cursed the ugly dependency look code in old EJB2 code.

Even if you cannot switch to an EJB3, you can still improve your existing code.
This is a sample of a typical EJB2 bean:


public class BookingBean implements SessionBean {
private CustomerDAO customerDAO;
private HotelDAO hotelDAO;
public void ejbCreate() {
customerDAO = Locator.lookup(CustomerDAO.class);
hotelDAO = Locator.lookup(HotelDAO.class)
}
}


If you have a lot of session beans, based on top of a large set of DAO instances, all this becomes a maintenance nightmare. It is very obvious that the code in the ejbCreate() method is really superfluous.

What I want to achieve in the new version:


public class BookingBean implements SessionBean {
@Autowired private CustomerDAO customerDAO;
@Autowired private HotelDAO hotelDAO;
public void ejbCreate() {
// use automatic injection of instances from global context
}
}


The "global context" can be something like a Spring application context, a classic JNDI naming context, or anything you want. Using reflection and a little bit of generic code, you can move the ejbCreate() to a base class.

Remaining work to do to wire a session bean to the dependencies:

  1. extend from the correct base class

  2. annotate your dependencies



Related links: