Sobes.tech
Junior — Middle

How is the Dependency Injection principle implemented within the Spring framework?

sobes.tech AI

Answer from AI

In Spring, the principle of Dependency Injection (DI) is implemented through an Inversion of Control (IoC) Container, which manages the creation and wiring of objects (beans). The main ways to inject dependencies in Spring are:

  • Through constructor — dependencies are passed to the class constructor.
  • Through setters — dependencies are set via setter methods.
  • Through fields annotated with @Autowired — Spring automatically injects the required beans.

Spring scans classes marked with annotations (@Component, @Service, @Repository, etc.), creates their instances, and injects dependencies based on configuration (XML, Java configuration, or annotations).

Example of constructor injection:

@Component
public class UserService {
    private final UserRepository userRepository;

    @Autowired
    public UserService(UserRepository userRepository) {
        this.userRepository = userRepository;
    }

    // methods
}

Thus, Spring manages the lifecycle of objects and their dependencies, which simplifies testing and maintenance of the code.