Sobes.tech
Junior — Middle

How is dependency injection implemented within the Spring Framework?

sobes.tech AI

Answer from AI

Dependency Injection (DI) in the Spring Framework is implemented through the Spring container, which manages the lifecycle of objects and their dependencies.

Main methods of dependency injection in Spring:

  1. Through constructor — dependencies are passed via the class constructor parameters.
@Component
public class Service {
    private final Repository repository;

    @Autowired
    public Service(Repository repository) {
        this.repository = repository;
    }
}
  1. Through setters (Setter Injection) — dependencies are set via setter methods.
@Component
public class Service {
    private Repository repository;

    @Autowired
    public void setRepository(Repository repository) {
        this.repository = repository;
    }
}
  1. Through fields (Field Injection) — dependencies are injected directly into fields using the @Autowired annotation.
@Component
public class Service {
    @Autowired
    private Repository repository;
}

The Spring container scans components, creates necessary objects, and automatically injects dependencies, which simplifies managing relationships between classes and enhances testability of the code.

How is dependency injection implemented within the… - sobes.tech