Spring dependency injection tutorial

Injection:

Injection is a process of passing the dependency to a dependent object.

Dependency Injection (DI):

Dependency Injection (DI) is a design pattern that implements inversion of control principle for resolving dependencies. It allows a programmer to remove hard coded dependencies so that the application becomes loosely coupled and extendable.

Let us discuss object dependency with below example:

public class Student {
   private Address address;
 
   public Student() {
      address = new Address();
   }
}

In above example Student class requires an Address object and it is responsible for initializing and using the Address object. If Address class constructor is changed in future then we have to make changes in Student class also. This approach makes tight coupling between Student and Address objects. We can resolve this problem using dependency injection design pattern. i.e. Address object will be implemented independently and will be provided to Student when Student is instantiated by using constructor-based or setter-based dependency injection.

We are taking one more example here.

Consider a case when we want to implement sorting functionality. We have one implementation class InsertionSort which uses insertion sort algorithm for sorting. Now in our sorting test class, we will create the InsertionSort class object and call its sorting method.

public class SortingTest {
   private SortAlgorithm sortAlgorithm;
 
   public SortingTest() {
      sortAlgorithm= new InersionSort();
   }
}

Here SortAlgorithm is an interface which is implemented by InsertionSort class. Now let us think that we have one more sorting implementation using merge sort algorithm and we want to sort the numbers with merge sort algorithm. In this case also we have to change our implementation class i.e. we have to change SortingTest() constructor by replacing InersionSort() with MergeSort(). It again result into tight coupling. We can resolve this problem using dependency injection design pattern.

Types of dependency Injection:

1. Constructor-based Dependency Injection. 2. Setter-based Dependency Injection.

Dependency Injection Examples:

Please follow and like us:
Content Protection by DMCA.com