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

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

85,000 Subscribers are learning from our Free Videos on YouTube : JSP Servlets, Spring, Spring Boot, Spring MVC, Hibernate, Eclipse, Maven, JUnit, Mockito, Full Stack - React, Full Stack - Angular, Docker, Kubernetes, AWS, AWS Fargate, PCF and Azure


Here are the recommend articles to read next : Spring Interview Questions, Spring Boot Interview Questions, Microservices, Hibernate, Spring Security, REST API with Spring Boot, Full Stack with React, SOAP Web Services, Exception Handling, Embedded Servers, Spring Data Rest, Spring vs Spring MVC vs Spring Boot, Building Web Application and Spring Data JPA.

You can checkout all our 100+ articles here - All Articles.


FREE COURSES



Related Posts

Docker Tutorial for Beginners - with Java and Spring Boot

Learn about Docker - What is Docker? Why Is Docker Popular? How to create Docker Image for a Java Spring Boot App?

Devops Tutorial | DevOps with Docker, Kubernetes and Azure DevOps

What is DevOps? How is it different from Agile? What are the popular DevOps Tools? What is the role of Docker, Kubernetes and Azure DevOps in DevOps. Let's get started with a simple usecase.

Deploy Java Spring Boot Applications to AWS, Azure, GCP with Docker and Kubernetes

In this article, we focus our attention on the cloud. How to learn the cloud and deploy Java Spring Boot Applications to AWS, Azure, GCP with Docker and Kubernetes?

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.

Microservices with Spring Boot and Java - Part 1 - Getting Started

Let's learn the basics of microservices and microservices architectures. We will also start looking at a basic implementation of a microservice with Spring Boot. We will create a couple of microservices and get them to talk to each other using Eureka Naming Server and Ribbon for Client Side Load Balancing. In part 1 of this series, lets get introduced to the concept of microservices and understand how to create great microservices with Spring Boot and Spring Cloud.

20+ Spring Boot Projects with Code Examples

At in28Minutes, we have created more than 20 projects with code examples on Github. We have 50+ articles explaining these projects. These code examples will you learn and gain expertise at Spring Boot.

REST API Best Practices - With Design Examples from Java and Spring Web Services

Designing Great REST API is important to have great microservices. How do you design your REST API? What are the best practices?

Index - 500+ Videos

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 React Java Full Stack Application with Maven

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

Creating a SOAP Web Service with Spring Boot Starter Web Services

Let's learn how to create a SOAP Web Service with Spring Boot Starter Web Services. We will take a Contract First approach by definining an XSD and exposing a WSDL from it.


Search