Sobes.tech
Junior — Middle

What methods are used to implement dependency injection in applications?

sobes.tech AI

Answer from AI

Dependency Injection (DI) is a pattern where an object receives its dependencies from outside rather than creating them itself. In Java, this is implemented in several ways:

  1. Constructor Injection: dependencies are passed through constructor parameters.
public class Service {
    private final Repository repository;

    public Service(Repository repository) {
        this.repository = repository;
    }
}
  1. Setter Injection: dependencies are set via setter methods after object creation.
public class Service {
    private Repository repository;

    public void setRepository(Repository repository) {
        this.repository = repository;
    }
}
  1. Interface Injection: the object implements an interface that allows dependencies to be injected.

  2. Framework usage: such as Spring, which automatically manages dependency injection through annotations (@Autowired) and configurations.

Each method has its pros and cons, but constructor injection is considered more reliable because dependencies are mandatory and the object is created in a correct state.

What methods are used to implement dependency… - sobes.tech