Dependency Injection

What is Spring Framework?

Spring is a lightweight framework for building Java applications. Unlike other frameworks, Spring can be used to create any application in java (stand-alone, web and JEE).

Why Spring Framework?

One of the great benefits of Spring framework is dependency Injection.  This means that the classes of the application should be loosely coupled to improve the reuse of those classes and test them independently. 

  1. Tight coupling :

To understand the problem when dependency injection is not used, bellow is an example of 2 tightly coupled classes.

- In this example, the RentCar object is dependent on the GasStation because the Object of GasStation is created inside the RentCar class.

- If we need to replace the GasolineFuel class by DieselFuel class, we need to do changes also in the RentCar Class. So, unnecessary tightly coupled code makes your application non-maintainable and decreases the test ability.

2. Loose coupling:

To make the classes loosely coupled, we can introduce interfaces. In this case, the class uses the interface as a dependency. That enables to replace dependencies without changing the class that uses them.

We will rewrite the example above as following.

Although RentCar depends on GasStationService, it does not care about what type of implementation (GasolineFuel or DieselFuel) is used in the application.

When the RentCar object is created, it should create or inject the object of the interface GasStationService in the RentCar class through the constructor argument (We can also use the setter to inject the dependency). Passing the newly created class (DieselFuel) throught the constructor does not require changes in the RentCar class.

The traditional method of managing dependency injection does work but using Spring framework make much easier. Spring DI provides two ways of DI:

  1. Using the constructor
  2. Using the setter method

In the next topic, we will see how to setup a Spring application using Maven and implement examples of dependecies injection using contructor and setter method.


Spring Framework – Overview.

Chris Schaefer; Rob Harrop; Clarence Ho. Pro Spring,Fourth EditionApress, 2014

Add a comment