Expert Spring MVC and Web Flow

(Dana P.) #1

implement IoC. Dependency Injection is another technique to implement, which we will dis-
cuss in the following section.


Dependency Injection


The concept of Dependency Injection is core to the Spring Framework. A specialization of Inver-
sion of Control, Dependency Injection is a technique that frameworks use to wire together an
application. The framework performs the work of connecting an application’s dependencies
together, removing the wiring logic and object creation from the application code completely.
We will contrast Dependency Injection with an older technique named the Service Loca-
tor pattern. We will show how the Service Locator pattern harms the testability and flexibility
of an application. We then show how Dependency Injection, and Spring’s implementation, fix
this issue.
In nearly all applications there are at least two participants, and these two participants
are required to somehow collaborate. The trick is to connect these two objects without locking
in the connection or requiring a certain environment to even exist for the connection to be
made.
For our example, we will consider the following use case. A cash register must obtain up-
to-date prices for items being purchased. The prices are stored and calculated inside a large
legacy system, but the cash register is physically located at the point of sale. The CashRegister
object must have a reference to the price database to perform its work.
We begin by defining the interface to represent the cash register. It has one method,
calculateTotalPrice, which takes a shopping cart and returns the total price for all items
in the cart.


public interface CashRegister {
public BigDecimal calculateTotalPrice(ShoppingCart cart);
}


Next, we define the interface for the service that will provide the real time price lookup.
This interface has one method, lookupPrice, to return the price for an item.


public interface PriceMatrix {
public BigDecimal lookupPrice(Item item);
}


Finally, we will create the implementation of the CashRegisterinterface. It simply creates
its own dependency, an instance of PriceMatrix.


public class CashRegisterImpl implements CashRegister {
private PriceMatrix priceMatrix = new PriceMatrixImpl();


public BigDecimal calculateTotalPrice(ShoppingCart cart) {
BigDecimal total = new BigDecimal("0.0");
for (Item item : cart.getItems()) {
total.add(priceMatrix.lookupPrice(item));
}
return total;
}
}


CHAPTER 2 ■SPRING FUNDAMENTALS 11
Free download pdf