Dependency Injection

From OasisSoftTech.com - Knowledge Base/Java/Springframework/Microservices/Cloud-AWS/AI
Jump to: navigation, search

What is Dependency Injection?

Dependency injection is a pattern through which to implement IoC, where the control being inverted is the setting of object’s dependencies.

The act of connecting objects with other objects, or “injecting” objects into other objects, is done by an assembler rather than by the objects themselves.

Here’s how you would create an object dependency in traditional programming:

public class Store {
    private Item item;
  
    public Store() {
        item = new ItemImpl1();    
    }
}

In the example above, we need to instantiate an implementation of the Item interface within the Store class itself.

By using DI, we can rewrite the example without specifying the implementation of Item that we want:

public class Store {
    private Item item;
    public Store(Item item) {
        this.item = item;
    }
}