Junior — Middle
How did you inject dependencies of Beans in your previous project?
sobes.tech AI
Answer from AI
Dependency Injection in Java is usually implemented using the Spring Framework, where objects (Beans) are created and managed by the Spring container.
Main methods of injecting dependencies into Beans:
- Through constructor — dependencies are passed via the class constructor parameters.
@Component
public class Service {
private final Repository repo;
@Autowired
public Service(Repository repo) {
this.repo = repo;
}
}
- Through setters — dependencies are set via setter methods.
@Component
public class Service {
private Repository repo;
@Autowired
public void setRepository(Repository repo) {
this.repo = repo;
}
}
- Through fields — using the
@Autowiredannotation directly on the field.
@Component
public class Service {
@Autowired
private Repository repo;
}
In my projects, I most often used constructor injection because it simplifies testing and makes dependencies explicit.