Easy learning with example program codes

Dependency Injection or Inversion principle

It is a SOLID design principle and represent “D” on the SOLID acronym. According to dependency inversion principle code should depends upon abstractions rather than upon concrete details. We should design our software in such a way that various modules can be separated from each other using an abstract layer to bind them together. BeanFactory in spring framework represents the classical use of this principle. All spring framework modules are provided as separate components which can work together by simply injected dependencies in other module.


Injection is a process of passing the dependency to a dependent object.

Dependency Injection (DI):

Dependency Injection (DI) is a design pattern that implements inversion of control principle for resolving dependencies. It allows a programmer to remove hard coded dependencies so that the application becomes loosely coupled and extendable.

Let us discuss object dependency with below example:

public class Student {
   private Address address;
   public Student() {
      address = new Address();

In above example Student class requires an Address object and it is responsible for initializing and using the Address object. If Address class is changed in future then we have to make changes in Student class also. This approach makes tight coupling between Student and Address objects. We can resolve this problem using dependency injection design pattern. i.e. Address object will be implemented independently and will be provided to Student when Student is instantiated by using constructor-based or setter-based dependency injection.

You can read following topics for dependency injection:

Spring dependency injection tutorial.
Spring constructor based injection tutorial.
Constructor injection type ambiguities tutorial.
Setter based dependency injection tutorial.
Spring dependency injection collections tutorial.


Please follow and like us:

Copyright © 2020 CodesJava Protection Status