Spring - What is Inversion of Control (IoC)
Introduction
Inversion of Control (IoC), also called as Dependency Injection (DI) is a process where Objects defines their dependencies, meaning that the other objects that it works with, defined through Constructor arguments, Factory method arguments or the properties set on the Object. This process allows an Object to decouple direct dependency other Objects at the time of instantiation or creation.
Contents
Problem with the way objects created that are tightly coupled
Let's understand this with an example, say we are creating an application called Notepad
SpellChecker
LettersCounter
If you visualize traditional way of implementing Notepad application, where Notepad
SpellChecker
LettersCounter

As you observe in below code, when the Notepad is instantiated, it automatically instantiating its dependencies as well.
public class Notepad {
private SpellChecker spellChecker;
private LettersCounter lettersCounter;
public Notepad() {
this.spellChecker = new SpellChecker();
this.lettersCounter = new LettersCounter();
}
}
How Inversion of Control (IoC) removes the dependency
Inversion of Control (IoC) removes this direct dependency on Object by introducing an abstraction between an Object and its dependencies. lets's understand this with the same example discussed above.
Below diagram shows Inversion of Control way of implementing this, where Notepad
SpellChecker
LettersCounter
DependencyInjector

As you observe in below code in the constructor, we are passing SpellChecker
LettersCounter
Notepad
public class Notepad {
private SpellChecker spellChecker;
private LettersCounter lettersCounter;
public Notepad(SpellChecker spellChecker, LettersCounter lettersCounter) {
this.spellChecker = spellChecker;
this.lettersCounter = lettersCounter;
}
}
This process also has below advantages.
- It provides a clear abstraction layer (
andSpellChecker
could be extracted as Interfaces), so that we could pass any implementation without changing the Notepad class.LettersCounter
- It makes unit testing easy with mocking frameworks such as Mockito by simply injecting Mocked objects as there is no direct dependency between Objects.
Spring Framework adoption of Inversion of Control(IoC)
Spring Framework implemented with the Inversion of Control at the core and it created a component called Spring IoC Container, on top of adopting IoC pattern, it also added other features like Aspect Oriented Programming (AOP) and Injecting Objects via Configuration (XML, YAML and Annotation based) etc.
In Spring Framework, there are mainly two components Beans
Configuration
Spring's IoC container acts as an Engine that is responsible creating, configuring, assembling and managing the beans using the meta data supplied.

Above diagram shows how the Spring IoC takes Beans and application configuration as inputs and serves the application as ready to use components.