What Is Spring Dependency Injection

From the documentation, Dependency injection (DI) is a process whereby objects define their dependencies, that is, the other objects they work with, only through constructor arguments, arguments to a factory method, or properties that are set on the object instance after it is constructed or returned from a factory method. The container then injects those dependencies when it creates the bean. This process is fundamentally the inverse, hence the name Inversion of Control (IoC), of the bean itself controlling the instantiation or location of its dependencies on its own by using direct construction of classes, or the Service Locator pattern.

The Spring Framework Inversion of Control (IoC) component is the nucleus of the framework. It uses dependency injection to assemble Spring-provided (also called infrastructure components) and development-provided components in order to rapidly wrap up an application.
Check out how Spring IOC Works with Example
Figure: Spring IoC purpose

Advantages of Dependency Injection

  • Decoupling: The code is cleaner with the DI principle and decoupling is more effective when objects are provided with their dependencies.
  • Easier to test: As such, your classes become easier to test, in particular when the dependencies are on interfaces or abstract base classes, which allow for stub or mock implementations to be used in unit tests.
DI exists in two major variants :
  • Constructor-based dependency injection
  • Setter-based dependency injection.

Constructor-based dependency injection

Constructor-based DI is accomplished by the container invoking a constructor with a number of arguments, each representing a dependency.

In the below diagram, the highlighted part shows the Constructor-based dependency injection.

Setter-based dependency injection

Setter-based DI is accomplished by the container calling setter methods on your beans after invoking a no-argument constructor or no-argument static factory method to instantiate your bean.
The following example shows a class that can only be dependency-injected using pure setter injection. This class is conventional Java.
In the below diagram, the highlighted part shows the setter-based dependency injection.
Read more at https://www.javaguides.net/2018/06/guide-to-dependency-injection-in-spring.html.


Comments