Junior — Middle
What ways can dependency injection for Beans be implemented in an application?
sobes.tech AI
Answer from AI
In Java, dependency injection (DI) for Beans can be implemented in several ways:
- Through constructor — dependencies are passed to the class constructor. This is the most preferred method as it allows creating immutable objects and simplifies testing.
public class Service {
private final Repository repo;
public Service(Repository repo) {
this.repo = repo;
}
}
- Through setters (Setter Injection) — dependencies are set via setter methods after the object is created.
public class Service {
private Repository repo;
public void setRepository(Repository repo) {
this.repo = repo;
}
}
- Through fields (Field Injection) — dependencies are injected directly into class fields using annotations, for example,
@Autowiredin Spring.
public class Service {
@Autowired
private Repository repo;
}
- Through factory methods or configuration classes — creation and binding of Beans occur in configuration classes or XML.
Each method has its pros and cons, but in modern applications, constructor injection or Spring annotations for automatic dependency binding are most commonly used.