Tutorialspoint examples

Learn java tutorial with examples for beginners online

Dependency Injection or Inversion principle


The object oriented design principles are used to achieve highly cohesive and loosely couple solution. Design principles provides us a way to create the clean and modular design.

The SOLID principles of Object Oriented Design include following five principles:

  • Single Responsibility Principle (SRP)
  • Open Closed Design Principle (OCP)
  • Liskov Substitution Principle (LSP)
  • Interface Segregation Principle (ISP)
  • Dependency Injection or Inversion principle (DIP)

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:

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.

 

Download tutorialspointexamples Android App
Copyright © 2018 Tutorialspoint examples DMCA.com Protection Status