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:
- Through constructor — dependencies are passed via the class constructor parameters. This is the most recommended way, as it allows fields to be
finaland makes testing easier.
@Component
public class Service {
private final Repository repository;
public Service(Repository repository) {
this.repository = repository;
}
}
- 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;
}
}
- Through fields (Field Injection) — dependencies are injected directly into fields using the
@Autowiredannotation. 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.