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.

Congratulations! You are reading an article from a series of 50+ articles on Spring, Spring Boot , Hibernate, Full Stack, Cloud and Microservices. We also have 20+ projects on our Github repository. For the complete series of 50+ articles and code examples, click here.

Join 300,000 Learners!

Learn Spring Boot in 10 Steps - FREE Course

Next Steps

Image

Image

Image

Image

Image

Image

Image

Image

Image

Image

Image

Image

Image

Image

Image

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 and Spring Boot Video Tutorials for Beginners

At in28Minutes, we are creating a number of tutorials with videos, articles & courses on Spring Boot for Beginners and Experienced Developers. Here's a list of video tutorials and courses for you

Creating Spring Boot and Vue JS CRUD Full Stack Application with Maven

This guide helps you create a full stack application with all the CRUD (Create, Read, Update and Delete) features using Vue JS as Frontend framework and Spring Boot as the backend REST API. We use Maven as the build tool.

Software Design - Separation Of Concerns - with examples

Software architects and programmers love having Seperation of Concerns. What is it? Why is it important? Let's get started.

Object Oriented Software Design - Solid Principles - with examples

Software design is typically complex. Object oriented design takes it to the next level. There are a number of design patterns and other stuff to be aware of. Can we make things simple? What are the goals to aim for when you are doing object oriented design? SOLID Principles is a great starting point for Object Oriented Design.

Software Design - Open Closed Principle - with examples

Open Closed Principle is one of the SOLID Principles. You want your code to be easily extended. How do you achieve it with minimum fuss? Let's get started.

Software Design - What is Dependency Inversion Principle?

Dependency Inversion Principle is one of the important SOLID Principles. Dependency Inversion Principle is implemented by one of the most popular Java frameworks - Spring. What is it all about? How does it help you design good applications?

Introduction to Four Principles Of Simple Design

With agile and extreme programming, the focus is on keeping your design simple. How do you keep your design simple? How do you decide whether your code is good enough?

Software Design - Single Responsibility Principle - with examples

For me, Single Responsibility Principle is the most important design principle. What is Single Responsibility Principle? How do you use it? How does it help with making your software better? Let's get started.

What is an In Memory Database?

In this article, we understand what the term "In-Memory Database" actually means. We see what scenarios they can be used, and why they are important.