EDUCBA

EDUCBA

MENUMENU
  • Explore
    • Lifetime Membership
    • All in One Bundles
    • Fresh Entries
    • Finance
    • Data Science
    • Programming and Dev
    • Excel
    • Marketing
    • HR
    • PDP
    • VFX and Design
    • Project Management
    • Exam Prep
    • All Courses
  • Blog
  • Enterprise
  • Free Courses
  • Login
Home Software Development Software Development Tutorials Spring Tutorial Dependency Injection in Spring

Dependency Injection in Spring

Priya Pedamkar
Article byPriya Pedamkar

Updated July 10, 2023

Dependency Injection in Spring

Introduction to Dependency Injection in Spring

Dependency Injection (DI) is a design pattern that implements the Inversion of Control for resolving the dependencies at run-time, i.e., injecting the dependency object to the dependent object to use at run-time. The most important module in the Spring Framework is Core Container & Dependency Injection (DI) acts as the heart of Spring’s Core Container.

ADVERTISEMENT
Popular Course in this category
SPRING FRAMEWORK Course Bundle - 10 Courses in 1 | 2 Mock Tests

Start Your Free Software Development Course

Web development, programming languages, Software testing & others

Conventionally, Developers will have control over the code in creating the objects & injecting them at run time. Here, the Spring framework takes control of doing the activities mentioned above at run time; that’s why the term is coined as ‘Inversion of Control’ (IoC), i.e., the control is inverted!

How to Perform Dependency Injection in Spring?

Before we investigate the ways of performing Dependency Injection, it is important to know the different types of Dependency Injection Configurations. There are two different ways of Dependency Injection Configurations.

  • XML based Configuration
  • Java Annotation-based Configurations

This article will focus on Java Annotation-based Configuration, which is the most advanced, easy to implement, and used widely across the software industry. Also, it is important to know the definition below before diving deep into implementing Dependency Injection.

  • Beans
  • Autowiring

In Spring Terminology, Objects that act as your application’s backbone and are managed, i.e., instantiation, Configuration & assembly by the IoC Containers, are referred to as Beans.

Spring Framework helps us by providing a way to detect the relationship between the beans by reading the XML Configuration file or scanning the Java annotations when booting up the application. The IoC Container – Bean Factory takes up this task, which will create the objects & wire the dependencies. Since Spring Framework does this process automatically, it is called Autowiring, i.e., Automatic Wiring!

With Java Annotation Configurations, developers wire beans by using the @Autowired annotation.

Different Ways of Dependency Injection

As per Java Annotation Configuration, Dependency Injection can be performed in three different ways. They are as follows.

  • Constructor-based Dependency Injection
  • Setter-based Dependency Injection
  • Field or Property-based Dependency Injection

Let us see one by one in detail with real-time examples & code snippets.

1. Constructor Based Dependency Injection

Constructor-based Dependency Injection refers to the use of the @Autowired annotation on top of a class constructor. Let us witness the usage of Constructor-based Dependency Injection with a real-time example.

POJO Class: EmployeeMasterDetails class

Dependency Injection - Constructor Based 1

Controller: CompanyMasterDetails class

Dependency Injection - Dependency Injection - Constructor Based 2

The code creates the EmployeeMasterDetails class as a component using the @Component annotation on line 16. Spring will automatically recognize this during the initialization/booting up of the application & will make a bean object using Bean Factory for EmployeeMasterDetails class.

After this, when Spring detects that the EmployeeMasterDetails bean object has been Autowired (using @Autowired) into the CompanyMasterDetails class constructor (line 18), the bean object created for EmployeeMasterDetails will be injected into CompanyMasterDetails class via constructor.

In this way, the Spring Framework will perform the Dependency Injection automatically. So, if you notice here, the developer has not created an object by using the “new” keyword in CompanyMasterDetails class, thereby removing the tight coupling between the CompanyMasterDetails class & EmployeeMasterDetails object.

2. Setter Based Dependency Injection

Setter-based Dependency Injection refers to the use of the @Autowired annotation on top of the setter method of a class. Let us witness Setter-based Dependency Injection’s usage with a real-time example.

POJO Class: EmployeeMasterDetails class

Setter Based - 1

Controller: CompanyMasterDetails class

Setter Based - 2

Similar to constructor based Dependency Injection, here the Autowiring takes place using the setter method at line no.18. The bean object created for EmployeeMasterDetails class will be Autowired & injected via the setter method in CompanyMasterDetails class.

3. Field or Property-Based Dependency Injection

Field-based Dependency Injection refers to the use of the @Autowired annotation on top of a field or property in a class. Let us witness the usage of Field-based Dependency Injection with a real-time example.

POJO Class: EmployeeMasterDetails class

Property Based -1

Controller: CompanyMasterDetails class

Property Based -2

Similar to Constructor-based Dependency Injection, here the Autowiring takes place using the field ‘empMasterDetails‘ at line no.16. The bean object created for EmployeeMasterDetails class will be Autowired & injected via the field ’empMasterDetails’ in CompanyMasterDetails class.

Fallback or Error Handling Cases.

Suppose there is more than one bean of the same type; the Spring Framework will get confused to inject the appropriate dependency. At this point, we will be running into the NoUniqueBeanDefinitionException.

To properly handle this, annotations from either @Primary or @Qualifier and the @Autowired annotation should be utilized.

  • @Primary annotation: Gives priority to the other beans of the same type.
  • @Qualifier annotation: Differentiates between the other beans by providing a unique qualifier name.

Advantages of Dependency Injection

Some of the advantages are as follows.

  • Primarily Dependency Injection helps achieve loosely coupled architecture by removing the tight coupling/dependency between a class & its dependence.
  • As the dependency between objects is loosely coupled, it helps the developers test the module by injecting the dependent Mock Objects (for example, using Spring Mockito).
  • Dependency Injection removes unnecessary dependencies between the classes.
  • As the modules are independent of each other & can be injected, the scope of making the component reusable is very high.
  • Maintenance of the System becomes easy.

Disadvantages of Dependency Injection

Some of the disadvantages are as follows.

  • Dependency Injection makes it difficult to trace the code as the developer needs to refer to more files (such as XML Configurations) to understand how the system behaves.
  • As the Spring Framework takes care of the control rather than the developer, it will be difficult for the developers to understand how things work in the background & also to have customization.
  • Dependency Injection allows loose coupling, increasing the number of Interfaces & classes.

Conclusion

So, in a nutshell, Dependency Injection helps the developers to achieve loose couplings between the classes. In this article, we have covered in-depth of Dependency Injection, its advantages & disadvantages & different ways of performing dependency injection with real-time examples & code snippets.

Recommended Articles

This is a guide to Dependency Injection in Spring. Here we discuss the introduction, How to perform dependency injection in Spring, along with advantages and disadvantages. You can also go through our other suggested articles to learn more –

  1. Spring Boot Versions
  2. Spring Boot Application
  3. XPath Injection
  4. Spring Architecture
ADVERTISEMENT
MICROSOFT POWER BI Course Bundle - 8 Courses in 1
34+ Hours of HD Videos
8 Courses
Verifiable Certificate of Completion
Lifetime Access
4.5
ADVERTISEMENT
CYBER SECURITY & ETHICAL HACKING Course Bundle - 13 Courses in 1 | 3 Mock Tests
64+ Hours of HD Videos
13 Courses
3 Mock Tests & Quizzes
Verifiable Certificate of Completion
Lifetime Access
4.5
ADVERTISEMENT
MICROSOFT AZURE Course Bundle - 15 Courses in 1 | 12 Mock Tests
63+ Hour of HD Videos
15 Courses
12 Mock Tests & Quizzes
Verifiable Certificate of Completion
Lifetime Access
4.5
ADVERTISEMENT
KALI LINUX Course Bundle - 6 Courses in 1
20+ Hours of HD Videos
6 Courses
Verifiable Certificate of Completion
Lifetime Access
4.5
Primary Sidebar
Footer
About Us
  • Blog
  • Who is EDUCBA?
  • Sign Up
  • Live Classes
  • Certificate from Top Institutions
  • Contact Us
  • Verifiable Certificate
  • Reviews
  • Terms and Conditions
  • Privacy Policy
  •  
Apps
  • iPhone & iPad
  • Android
Resources
  • Free Courses
  • Java Tutorials
  • Python Tutorials
  • All Tutorials
Certification Courses
  • All Courses
  • Software Development Course - All in One Bundle
  • Become a Python Developer
  • Java Course
  • Become a Selenium Automation Tester
  • Become an IoT Developer
  • ASP.NET Course
  • VB.NET Course
  • PHP Course

ISO 10004:2018 & ISO 9001:2015 Certified

© 2023 - EDUCBA. ALL RIGHTS RESERVED. THE CERTIFICATION NAMES ARE THE TRADEMARKS OF THEIR RESPECTIVE OWNERS.

EDUCBA

*Please provide your correct email id. Login details for this Free course will be emailed to you

Let’s Get Started

By signing up, you agree to our Terms of Use and Privacy Policy.

EDUCBA
Free Software Development Course

Web development, programming languages, Software testing & others

By continuing above step, you agree to our Terms of Use and Privacy Policy.
*Please provide your correct email id. Login details for this Free course will be emailed to you

EDUCBA

*Please provide your correct email id. Login details for this Free course will be emailed to you
EDUCBA

*Please provide your correct email id. Login details for this Free course will be emailed to you
EDUCBA Login

Forgot Password?

By signing up, you agree to our Terms of Use and Privacy Policy.

This website or its third-party tools use cookies, which are necessary to its functioning and required to achieve the purposes illustrated in the cookie policy. By closing this banner, scrolling this page, clicking a link or continuing to browse otherwise, you agree to our Privacy Policy

Loading . . .
Quiz
Question:

Answer:

Quiz Result
Total QuestionsCorrect AnswersWrong AnswersPercentage

Explore 1000+ varieties of Mock tests View more

🚀 Extended Cyber Monday Price Drop! All in One Universal Bundle (3700+ Courses) @ 🎁 90% OFF - Ends in ENROLL NOW