Java Reference
In-Depth Information
IOC is not a new concept and has been around for a long time. EJBs, for example,
supports IOC. The various EJB components such as session, entity, and message-driven
beans lay down specific contracts with the container by implementing the methods
defined in different interfaces. The session bean, for example, implements the ejbActivate
and ejbPassivate life-cycle methods defined in the javax.ejb.SessionBean interface. How-
ever, these methods are never called from other methods of the session bean; rather, the
container calls these methods at different times during the life cycle of the bean, thus
inverting control. Message-driven beans, for instance, implement the onMessage method
of the javax.jms.MessageListener interface. It is the responsibility of the container to
invoke this method on the event of a message arrival.
Dependency Injection
It is common for developers to believe that IOC and DI are the same thing. This is incor-
rect, and I want to make it clear right at the outset that they are two different yet related
concepts. Just as IOC deals with inverting the control flow in an application, DI describes
how one object resolves or finds other objects on which it needs to invoke some meth-
ods. There are several ways to achieve DI, and one such strategy is IOC. I will explain the
different DI strategies one by one in the next few sections.
Direct Instantiation
Direct instantiation is the simplest form of DI. The dependent object is directly instanti-
ated using the new operator, as shown in Listing 2-1.
Listing 2-1. FormulaOneDriver.java : Using Direct Instantiation
public class FormulaOneDriver{
public Car getCar(){
Car car = new FerrariCar();
return car;
}
}
The Formula 1 driver object ( FormulaOneDriver ) needs a car to drive. Hence, it creates
an instance of the Car object directly and uses it. Direct instantiation increases coupling
and scatters object creation code across the application, making it hard to maintain and
unit test.
 
Search WWH ::




Custom Search