Sobes.tech
Senior

Tell me about dependency injection methods in Spring

sobes.tech AI

Answer from AI

In Spring, there are several ways to perform dependency injection:

  1. Through constructor — dependencies are passed via the class constructor parameters. This is the most recommended way, as it allows fields to be final and makes testing easier.
@Component
public class Service {
    private final Repository repository;

    public Service(Repository repository) {
        this.repository = repository;
    }
}
  1. Through setters (Setter Injection) — dependencies are set via setter methods. Used when the dependency is optional or can change.
@Component
public class Service {
    private Repository repository;

    @Autowired
    public void setRepository(Repository repository) {
        this.repository = repository;
    }
}
  1. Through fields (Field Injection) — dependencies are injected directly into fields using the @Autowired annotation. Less preferred, as it makes testing harder and breaks encapsulation.
@Component
public class Service {
    @Autowired
    private Repository repository;
}

Each method has its pros and cons, but constructor injection is considered best practice in modern Spring applications.