What is dependency injection in Java?

In object-oriented programming, a class may rely on objects of other classes. A dependency injection is a strategy that is used to separate the creation of dependency objects from the class that needs them.

To help you understand, the following code snippet shows no dependency injection:

class Question {
private Answer answer;
public Question(){
answer = new Answer();
}
}

As opposed to this, the following shows a dependency injection:

class Question {
private Answer answer;
public Question(Answer ans){
this.answer = ans;
}
}

There are three different types of dependency injections:

Constructor injection

Constructor injection is shown in the first code example. The dependent class receives the object it requires as a parameter of the constructor.

Setter injection

The dependent class has a public setter method through which the dependency is injected. An example is given in the code below:

class Building {
private Room room;
public setRoom(Room room){
this.room = room;
}
}

Interface injection

An interface provides an injector method that is responsible for injecting the dependency to any class that may require it. The client class has to implement the interface and override the injector method. For example:

public interface Injector {
public void injectDependency(Dependency object);
}
public class Client implements Injector {
private Dependency dependentObject;
@Override
public void injectDependency(Dependency object){
this.dependentObject = object;
}
}

Advantages of dependency injection

  • Makes testing easier by enabling the use of mock objects or stubs

  • Reduces coupling between client and dependency classes

  • Reduces boilerplate code since the initialization of all dependencies is done once by the injector

  • The code is easier to maintain and reuse

Free Resources