Learn Java for Web Development

(Tina Meador) #1

212 CHAPTER 5: Building Java Web Applications with Spring Web MVC


Key Objectives of the Spring Framework


Dependency injection is not the only key benefit of using the Spring Framework. The goal of
the Spring Framework is to simplify the complexity of developing an enterprise application. This
complexity manifests itself in an enterprise application in several ways, and most enterprise
applications prior to the Spring Framework were inadvertently afflicted with few or even all of the
following tribulations:


   Tight coupling
 Cross-cutting concerns
 Boilerplate code

Fundamentally, Spring enables you to build applications from POJOs and apply enterprise services
nonintrusively to POJOs so that the domain model has no dependencies on the framework itself.
Thus, the driving force behind the Spring Framework was to promote best practices in Java EE
development by enabling a POJO-based programming model.


Dealing with Tight Coupling Using Dependency Injection

Now let’s see how Spring enables loose coupling through dependency injection with the help of a
simple stand-alone application. The code for this application is available in a downloadable archive
on the Apress web site. In addition, this application will be a preamble into the Spring forest. Listing
5-10, 5-11, and 5-12 illustrate the hierarchy of service provider objects and the dependencies of the
VehicleService illustrated in Listing 5-13.


Listing 5-10. Vehicle Interface


public interface Vehicle {
public String drive();
}


Listing 5-11. Vehicle Implementation: Bike


public class Bike implements Vehicle{
public String drive() {
return " driving a bike";
}
}


Listing 5-12. Vehicle Implementation: Car


public class Car implements Vehicle {


public String drive() {
return " driving a car";
}
}


These service provider objects are used by the class VehicleService, as illustrated in Listing 5-13,
which is then used by the client object, as illustrated in Listing 5-14.

Free download pdf