Sobes.tech
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:

  1. 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;
    }
}
  1. 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;
    }
}
  1. Field injection — dependencies are injected directly into class fields, usually with annotations (e.g., @Autowired in Spring).
public class Service {
    @Autowired
    private Repository repo;
}

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