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

  1. 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;
    }
}
  1. Through setters — dependencies are set via setter methods.
@Component
public class Service {
    private Repository repo;

    @Autowired
    public void setRepository(Repository repo) {
        this.repo = repo;
    }
}
  1. Through fields — using the @Autowired annotation 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.

How did you inject dependencies of Beans in your… - sobes.tech