Inversion of Control and Dependency Injection with Spring

Surabhibadal
3 min readJun 13, 2021

--

In this article, I will be covering the basics of Inversion of Control and Dependency Injection and then build upon the same to help you guys understand its purpose and its usage.

Spring IoC Container

In the Spring framework, the interface ApplicationContext represents the IoC container. The Spring container is responsible for instantiating, configuring, and assembling objects known as beans, as well as managing their life cycles. In order to assemble beans, the container uses configuration metadata, which can be in the form of XML configuration or annotations.

The Spring framework provides several implementations of the ApplicationContext interface: ClassPathXmlApplicationContext and FileSystemXmlApplicationContext for standalone applications, and WebApplicationContext for web applications.

Inversion of Control

Inversion of Control is a principle in which control of objects is transferred to a Spring container. Using this the dependencies between the classes are registered and resolved at runtime by the Spring framework.

Dependency Injection

Dependency injection is a pattern we can use to implement IoC, where the control being inverted to Spring Container. It is used to reduce the dependency between modules, making it easier to change modules, maintain code and testing

There are 2 types of Dependency Injection

  1. Constructor Injection: The dependencies will be injected into the class by a container through the constructor of that class. This is the most common way.
BaseBallCoach.java
SpringApp.java (Main App)
applicationcontext.xml

2. Setter Injection: Dependencies will be passed into a class via Setter functions.

CricketCoach.java
SpringApp.java
applicationcontext.xml

Pros

  1. Code is easy to maintain, easy to replace modules
  2. It is very easy to test and write Unit Test
  3. Increases code reusability
  4. Easily see relationships between modules

Cons

  1. Increase the complexity of the code.
  2. The objects are initialized entirely from the beginning, which can reduce performance
  3. Using an interface can sometimes be difficult to debug because it is not known exactly which module is called.

Sign up to discover human stories that deepen your understanding of the world.

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

--

--

Surabhibadal
Surabhibadal

Written by Surabhibadal

0 Followers

Software Developer

No responses yet

Write a response