A class or an object (A
) is said to be dependent on another object or class (B
) when A
uses some functionality of B
.
Traditionally, A
is responsible for creating the dependent object B
itself.
class A{private B b = new B();//The rest}
This approach leads to highly coupled classes.
Now, suppose we want to change the type of dependent object from B
to some other class, C
. We will have to recreate class A
with its new dependency, C
.
In simple terms, dependency injection is supplying an object with what it needs instead of having the object create it themselves. This approach leads to loosely coupled classes, a desirable behavior.
The dependent class is called the Client class. Dependency is referred to as the Service class.
In dependency injection, dependencies are provided to classes at run time rather than at compile time. A dependency injection is sort of the middleman in our code, as it does all the work of creating the desired dependency object B
and providing it to class A
.
class A{// Constructor Injectionprivate B b;A(B b) {this.b = b;}//Setter injectionvoid setB(B b) {this.b = b;}}
Constructor injection: A class constructor supplies the dependencies.
Setter injection: Injector injects the dependency through a setter method exposed by the client.
Interface injection: Injector class injects the dependency object into the dependent class.
Free Resources