Dependency Injection in Spring Boot

Nimasha Madhushani
LinkIT
Published in
4 min readJan 11, 2023
Artwork by Author

Hi Enthusiasts…..,🤗

Java programming has never been quicker, simpler, or safer thanks to Spring😎. Spring is the most widely used Java framework in the world because of its emphasis on productivity, speed, and simplicity. Furthermore, it helps solve real-time technical problems.

So.., here we go to get a better understanding of dependency injection and how it can be used in Spring Framework…,

📝 What is Spring Framework?

Spring is a lightweight framework.

🟢 The conceptual weight of a framework is referred to as “lightweight” in this sentence. A lightweight framework like Spring has little impact on an application.

It might be considered a framework of frameworks since it supports several different frameworks, including Struts, Hibernate, Tapestry, EJB, JSF, etc. In a deeper context, the framework can be described as a structure where we attempt to solve numerous technological issues.

🟣 Struts — open source framework that extends the Java Servlet API and employs a Model, View, Controller (MVC) architecture. It enables you to create maintainable, extensible, and flexible web applications based on standard technologies

🟣 Hibernate — ORM tool used for saving the state of the Java object in the database. By default, Spring uses Hibernate as the default JPA vendor.

🟣 Tapestry — Open-source framework for developing Java web applications that are dynamic, reliable, and highly scalable. Tapestry works in any servlet container or application server since it enhances and expands upon the standard Java Servlet API.

🟣 EJB[Enterprise Java Beans] —Development architecture for building highly scalable and robust enterprise level applications.

🟣 JSF[Java Server Faces] — Java-based web application framework intended to simplify development integration of web-based user interfaces.

🌀 The essential component of Spring Framework is Spring IoC Container. It generates the objects, sets up and assembles their dependencies, and controls every aspect of their life cycle. To handle the parts that make up the application, the container makes advantage of Dependency Injection (DI).

📝 What is Dependency Injection?

Dependency injection (DI), which is used in the design of software using object-oriented programming (OOP), involves providing a resource that a specific piece of code needs. The needed resource is known as dependence, and it is frequently an element of the application itself.

If a software component needs to communicate with other resources in order to fulfill its intended function, it must be aware of other resources’ identities, locations, and communication protocols. Mapping the locations of each necessary resource is one method of arranging the code. Another approach is to implement dependency injections and delegate the task of locating the resources to an external piece of code.

📌 There are 3 types of dependency injections.

  1. Constructor-Based Dependency Injection
  2. Setter-Based Dependency Injection
  3. Field-Based /Property-Based Dependency Injection

📝 How to use Dependency Injection?

📚 Constructor-Based Dependency Injection

Constructors are used to inject the dependency.

📌 Heart.java

import org.springframework.stereotype.Component;

@Component
public class Heart {
public void pumpBlood() {
System.out.println("Pumping Blood");
}
}

📌 Human.java

import jakarta.annotation.PostConstruct;
import org.springframework.stereotype.Component;

@Component
public class Human {
private Heart heart;

public Human(Heart heart) {
this.heart = heart;
}

@PostConstruct
public void Sound() {
heart.pumpBlood();
}
}

@PostConstruct

🔷 When the Spring Framework creates/initializes a particular bean.

🔷 Then after, the method which belongs to this @PostConstructshould be executed.

@Component

🔷 Automatically detect custom beans.

🔷 Scan the application for classes annotated with @Component

🔷 Instantiate them and inject any specified dependencies into them

🔷 Inject them wherever needed.

image by author
image by author
image by author

📚Setter-Based Dependency Injection

Setters are used to inject the dependency.

📌 Heart.java

import org.springframework.stereotype.Component;

@Component
public class Heart {
public void pumpBlood() {
System.out.println("Pumping Blood");
}
}

📌 Human.java


import jakarta.annotation.PostConstruct;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Component
public class Human {
private Heart heart;

public Heart getHeart() {
return heart;
}
@Autowired
public void setHeart(Heart heart){
this.heart=heart;
}

@PostConstruct
public void Sound() {
this.heart.pumpBlood();
}
}

@Autowired

🔷 If have only one constructor this annotation is not required.

🔷 Implementation is wired using this annotation. Autowire spring bean on setter methods, instance variable and constructor.

📚 Field-Based /Property-Based Dependency Injection

The property of the variable is used to inject the dependency.

📌 IRun.java [ Interface]

public interface IRun {
void run();
}

📌 Cat.java

import org.springframework.stereotype.Component;

@Component("Cat")
public class Cat implements IRun {
@Override
public void run() {
System.out.println("Cat runs...");
}
}

📌 Dog.java

import org.springframework.stereotype.Component;

@Component("Dog")
public class Dog implements IRun{
@Override
public void run(){
System.out.println("Dog runs...");
}
}

📌 Human.java

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Component;

@Component
public class Human {
@Qualifier("Dog")
@Autowired
private IRun run;
}

🟢 @Qualifier annotation is used to resolve the autowiring conflict, when there are multiple beans of same type.

🟡 “A bean is an object that is instantiated, assembled, and otherwise managed by a Spring IoC container.”

Here, Beans of IRun type,

🔹 Beans : Cat

🔹 Beans : Dog

Therefore, now Sping cannot separately identify two beans. Then we can apply @Qualifier annotation as the solution.

Yeeeah…., A little bit lengthy article. So….., it’s time to have a break…😊

I will bring you a mini blog with different annotations that we can use in Spring Framework and their uses as well.❣❣❣❣❣❣

Untill then have a nice day… ,Bye..Bye….👋👋👋👋

--

--