CHAPTER 5: Building Java Web Applications with Spring Web MVC 213
Listing 5-13. Vehicle Service
- public class VehicleService {
- private Vehicle vehicle = new Bike();
- public void driver() {
- System.out.println(vehicle.drive());
- }
- }
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
- public class VehicleApp {
- public static void main(String[] args) {
- VehicleService service = new VehicleService();
- service.driver();
- }
- }
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.