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
Let's understand this with an example, say we are creating an application called
If you visualize traditional way of implementing Notepad application, where
As you observe in below code, when the Notepad is instantiated, it automatically instantiating its dependencies as well.
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
As you observe in below code in the constructor, we are passing
This process also has below advantages.
- It provides a clear abstraction layer (
SpellChecker andLettersCounter could be extracted as Interfaces), so that we could pass any implementation without changing the Notepad class. - 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 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
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.