Sobes.tech
Junior — Middle

How is dependency injection implemented in Bean when they are detected in the context of Spring or similar frameworks?

sobes.tech AI

Answer from AI

In Spring, dependency injection (DI) into a Bean occurs automatically when components are detected in the application context. The main methods of injection are:

  1. Constructor-based — dependencies are passed through constructor parameters. Spring injects the required objects when creating the Bean.

  2. Setter-based (Setter Injection) — dependencies are set through setter methods annotated with @Autowired.

  3. Field-based (Field Injection) — class fields are annotated with @Autowired, and Spring injects the required objects directly.

Example of constructor injection:

@Component
public class Service {
    private final Repository repository;

    @Autowired
    public Service(Repository repository) {
        this.repository = repository;
    }
}

When Spring starts, it scans classes with annotations like @Component, @Service, @Repository and creates their instances, automatically resolving dependencies by type from the context. If there are multiple candidates, @Qualifier can be used for clarification.

Thus, dependency injection occurs through the Spring container, which manages the lifecycle of Beans and their relationships.

How is dependency injection implemented in Bean when… - sobes.tech