Junior — Middle
What methods are used to implement dependency injection in a Bean?
sobes.tech AI
Answer from AI
Dependency Injection (DI) in a Bean is usually implemented through:
- Constructor injection — dependencies are passed via the class constructor. This ensures dependencies are immutable after object creation.
public class Service {
private final Repository repo;
public Service(Repository repo) {
this.repo = repo;
}
}
- Setter injection — dependencies are set via setter methods after object creation.
public class Service {
private Repository repo;
public void setRepository(Repository repo) {
this.repo = repo;
}
}
- Field injection — dependencies are injected directly into class fields, usually with annotations (e.g.,
@Autowiredin Spring).
public class Service {
@Autowired
private Repository repo;
}
Each method has its pros and cons; the choice depends on context and framework.