Learn Java for Web Development

(Tina Meador) #1
CHAPTER 5: Building Java Web Applications with Spring Web MVC 213

Listing 5-13. Vehicle Service



  1. public class VehicleService {



  2. private Vehicle vehicle = new Bike();



  3. public void driver() {

  4. System.out.println(vehicle.drive());



  5. }



  6. }


   Line 3: In Listing 5-13, class Bike is the dependency of class VehicleService
and is instantiated on line 3. This is a case of tight coupling because the class
VehicleService is implementation-aware of the Vehicle object, which is Bike in
this case.

Listing 5-14 illustrates the stand-alone VehicleApp.


Listing 5-14. Stand-Alone VehicleApp



  1. public class VehicleApp {

  2. public static void main(String[] args) {

  3. VehicleService service = new VehicleService();

  4. service.driver();

  5. }

  6. }


As illustrated in Listing 5-14, VehicleService is implementation-aware of the Vehicle object and
hence tightly coupled to it. Now let’s decouple this application through the Spring Framework’s DI.
The first step is to create a Java project using the Eclipse IDE. Select File ➤ New ➤ Project and
then select Java Project Wizard from the wizard list. Name your project looselyCoupledApplication
using the wizard, as illustrated in Figure 5-2.

Free download pdf