Spring Basics - Dependency Injection and Inversion of Control


Developers starting with the Spring framework often get confused with terminology - Dependency, Dependency Injection and Inversion Of Control. In this article, we introduce you to the concepts of Dependency Injection and Inversion Of Control.

You will learn

  • What Is Dependency Injection?
  • Why do you need Dependency Injection?
  • What Is tight coupling?
  • What Is de-coupling?
  • How does Spring Framework provide Dependency Injection?
  • What Is Inversion Of Control?
  • What are good examples of inversion of control?
  • How does Spring Framework implement Inversion of Control?
  • Why Is Inversion of Control Important and what are its advantages?

Spring Framework

This is the third article in a series of articles on Spring Framework:

What Is Dependency Injection?

Dependency injection is the core feature of the Spring Framework. Dependency injection is a concept that is borrowed from the Dependency Inversion Principle (DIP).

Tight Coupling

Have a look at the following examples of code:

Example-1

	public class TodoBusinessService {
		TodoDataServiceImpl dataService = new TodoDataServiceImpl();
		//... 
	}

TodoBusinessService is directly creating an instance of TodoDataServiceImpl within itself.

Example-2

	public class ComplexAlgorithmImpl {
		BubbleSortAlgorithm bubbleSortAlgorithm = new BubbleSortAlgorithm();
		//...
	}

ComplexAlgorithmImpl is meant to perform a lot of complex logic, and one of the things it does is sorting. here, it is directly creating an instance of BubbleSortAlgorithm within itself.

These two examples highlight code with tight coupling.

Imagine what you need to do, if you want to change the sort algorithm to quicksort. You need to change the relevant code within ComplexAlgorithmImpl.

Hence, ComplexAlgorithmImpl is tightly coupled to BubbleSortAlgorithm, a specific sort algorithm.

Decoupling ComplexAlgorithmImpl

How do we decouple ComplexAlgorithmImpl from the specific sort algorithm?

We want it to be used with bubble sort, or quick sort, or radix sort, or any other sort. The solution is to make use of an interface.

Have a look at the following code:


	public interface SortAlgorithm {
		public int[] sort(int[] numbers);
	}

	@Component
	public class ComplexAlgorithmImpl {
		@Autowired
		private SortAlgorithm sortAlgorithm;	
		//...
	}

	public class BubbleSortAlgorithm implements SortAlogrithm {
		//...
	}

	public class QuickSortAlgorithm implements SortAlogrithm {
		//...
	}

Decoupling Explained

We have created an interface named SortAlgorithm that has sort() method defined. Specific sort algorithms all implement SortAlgorithm by overriding sort(). Here, ComplexAlgorithmImpl makes use of SortAlgorithm as a dependency by declaring it as a member. However, the actual implementation of SortAlgorithm needs to be passed in as a parameter to its constructor, or a setter method. The user decides which specific sort algorithm ComplexAlgorithmImpl gets to use.

Whichever class wants to make use of ComplexAlgorithmImpl needs to write code such as this:


	CompexAlgorithmImpl binarySearch = new ComplexAlgorithmImpl(new QuickSortAlgorithm());

Other classes may choose to pass in SortAlgorithm implementations for bubble sort, heap sort or radix sort.

Inversion of Control with ComplexAlgorithmImpl

Look at it from the perspective of ComplexAlgorithmImpl.

In the first approach, it took up the responsibility of selecting the specific sort algorithm. As a result, the specific BubbleSortAlgorithm was hard-coded.

In the second approach, the class which uses ComplexAlgorithmImpl gets to decide which specific sort algorithm is to be used.

There is a clear inversion of responsibility taking place. This is also called Inversion of Control or dependency inversion.

Dependency inversion results in loose coupling. ComplexAlgorithmImpl is not tied to a specific sort algorithm.

Dependency Injection In Spring

Now where does Spring framework come into picture?

Lets look at the code below:


	CompexAlgorithmImpl binarySearch = new ComplexAlgorithmImpl(new QuickSortAlgorithm());

In the above piece of code, we are manually creating the objects and tying them up with dependencies. In a typical application, we might have thousands of objects. Do you want to write the code for all it manually. How about having a framework that does this for you?

Let’s consider the following example:


	@Component
	public class ComplexAlgorithmImpl {
		@Autowired
		private SortAlgorithm sortAlgorithm;	
		//...
	}

When this code is run - Spring creates an instance of QuickSortAlgorithm which implements SortAlgorithm interface, and wires it into an instance of ComplexAlgorithmImpl.

This process, where the Spring framework identifies the beans, identifies the dependencies, and populates the dependencies inside the beans is called dependency injection.

Dependency Inversion And Dependency Injection

So far in this article, we have discussed two important concepts:

  • Dependency Inversion : We create loosely couple code by explicitly declaring dependencies, and introducing interfaces for them.
  • Dependency Injection : The Spring framework identifies beans and dependencies, and wires dependencies inside beans.

Do check out our video on the same topic:

image info

Summary

In this article, we talked about dependency injection. Dependency injection has its roots in a core SOLID principle of object oriented programming, named the Dependency Inversion principle. We saw how dependency inversion transforms tightly couple code into a loosely coupled one. Dependencies are explicitly identified, and classes that use them become flexible.

Dependency injection is a mechanism based on dependency inversion. The Spring framework identifies beans and dependencies, and autowires the dependencies into beans.

Related Posts

Spring Boot Tutorials for Beginners

At in28Minutes, we are creating a number of tutorials with videos, articles & courses on Spring Boot for Beginners and Experienced Developers. This resources will help you learn and gain expertise at Spring Boot.

Spring Boot Basics - What Is A Profile?

When we develop applications, we would want to be able to provide different application configuration in different environments? How do you achieve it with Profiles?

Spring Basics - What Is A Dependency?

Most important feature of Spring Framework is Dependency Injection. To understand Dependency Injection, you need to understand the concept of a Dependency.

Architecture of Spring Framework - Modularity and Spring Modules

One of the most important features of the Spring framework is its modularity. It is not one big monolith framework. What are Spring Modules? How are they organized? What is the architecture of Spring Framework?

What Are Spring Projects?

There are several important Spring Projects solving the needs of enterprises today. What are Spring Projects and how are they different from Spring Modules?

Spring Basics - Introduction To Spring Batch

Spring Batch is a lightweight, comprehensive batch framework that is designed for use in developing robust batch applications.

Spring Framework Basics - What Is Inversion Of Control?

Developers starting with the Spring framework often get confused with terminology - Dependency, Dependency Injection and Inversion Of Control. In this article, we introduce you to the concept of Inversion of Control.

Spring Boot Basics - Introduction To Spring Data and Spring Data JPA

In this article, we take a look at Spring Data and Spring Data JPA.

Spring Basics - Introduction To Spring Framework

In this article, we look to get an introduction to what the Spring framework is, and why it is so widely used.

Spring Boot Basics - Introduction To Spring Data Rest

Spring Data project provides common abstractions to integrate with different kinds of data stores. Spring Data Rest is part of the umbrella of Spring Data projects. It makes it easy to build hypermedia-driven REST web services, on top of Spring Data repositories.