Sobes.tech
Junior — Middle

What methods can be used to inject a dependent component into another object in the context of dependency injection?

sobes.tech AI

Answer from AI

Dependency Injection in Java can be implemented in several ways:

  1. Through Constructor — the dependent component is passed into the class constructor. This is the most common and recommended method, as it makes dependencies immutable and explicitly visible.
public class Service {
    private final Repository repository;

    public Service(Repository repository) {
        this.repository = repository;
    }
}
  1. Through Setter (Setter Injection) — the dependency is passed via a setter method after the object is created.
public class Service {
    private Repository repository;

    public void setRepository(Repository repository) {
        this.repository = repository;
    }
}
  1. Through Interface (Interface Injection) — the class implements an interface that contains a method for setting the dependency. This is used less frequently.

  2. Through Fields (Field Injection) — with annotations (e.g., @Autowired in Spring), the dependency is injected directly into the class field. Convenient, but complicates testing and violates encapsulation principles.

Each method has its pros and cons; the choice depends on the context and the framework used.

What methods can be used to inject a dependent… - sobes.tech