Spring Basics - Dependency Injection and Inversion of Control


Image


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?

Free Courses - Learn in 10 Steps

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.

Best Selling Udemy Courses

Image
Image Image Image Image Image Image Image Image Image

Join 450,000 Learners and 30+ Amazing Courses

350,000 Learners are learning everyday with our Best Selling Courses : Spring Boot Microservices, Spring, Spring Boot, Web Services, Hibernate, Full Stack React, Full Stack Angular, Python, Spring Interview Guide, Java Interview, Java Functional Programming, AWS, Docker, Kubernetes, PCF, AWS Fargate and Azure


Do not know where to start your learning journey? Check out our amazing learning paths:
Learning Path 01 - Spring and Spring Boot Web Applications and API Developer,
Learning Path 02 - Full Stack Developer with Spring Boot, React & Angular,
Learning Path 03 - Cloud Microservices Developer with Docker and Kubernetes,
Learning Path 04 - Learn Cloud with Spring Boot, AWS, Azure and PCF and
Learning Path 05 - Learn AWS with Microservices, Docker and Kubernetes


Subscribe

FREE COURSES



Related Posts

Writing Integration Tests for Rest Services with Spring Boot

Setting up a basic REST Service with Spring Boot is a cake walk. We will go one step further and add great integration tests!

Integrating Spring Boot and Spring JDBC with H2 and Starter JDBC

Learn using Spring Boot Starter JDBC to connect Spring Boot to H2 (in memory database) using Spring JDBC. You will create a simple project with Spring Boot. You will add code to the project to connect to a database using Spring JDBC. You will learn to implement the basic CRUD methods.

JUnit Tutorial for Beginners in 5 Steps

JUnit Tutorial for Beginners in 5 Steps. Setting up a basic JUnit example and understanding the basics of junit.

JPA and Hibernate Tutorial For Beginners - 10 Steps with Spring Boot and H2

JPA and Hibernate in 10 Steps with H2 - Setting up a basic project example with Spring Boot and in memory database H2. Its a cake walk.

Spring Boot Tutorial For Beginners in 10 Steps

Introduction to Spring Boot in 10 Steps. Learn the basics of Spring Boot setting up a basic project example with Spring Boot.

Spring Framework Tutorial for Beginners - Your First 10 Steps

Learn the basics of Spring Framework setting up a very simple example.

JPA and Hibernate Tutorial using Spring Boot Data JPA

Complete journey starting from JDBC to JPA to Spring Data JPA using an example with Spring Boot Data JPA starter project. We use Hibernate as the JPA Implementation.

Creating a Web Application with Spring Boot with JSP

Setting up a basic web application with Spring Boot is a cake walk. We will create a simple web application using Spring Initializr and add JSP features to it.

What is Spring Boot Auto Configuration?

Auto Configuration is the most important feature in Spring Boot. In this tutorial, we will learn important concepts about Auto Configuration with a couple of examples.

Unit Testing Rest Services with Spring Boot and JUnit

Setting up a Basic REST Service with Spring Boot is a cake walk. We will go one step further and add great unit tests to our RESTful Service.


Search