Sobes.tech
Junior — Middle

Can you explain the concept of dependency injection within the Spring Framework?

sobes.tech AI

Answer from AI

Dependency Injection (DI) in the Spring Framework is a pattern that allows objects to receive their dependencies from outside rather than creating them themselves. This enhances modularity, testability, and manageability of the code.

In Spring, DI is implemented through a container that manages the lifecycle and relationships between objects (beans). The main methods of injection are:

  • Through constructor
  • Through setters (setter methods)
  • Through fields (using annotations)

Example of dependency injection via constructor:

@Component
public class UserService {
    private final UserRepository userRepository;

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

    // methods
}

Here, Spring will automatically create and inject the required UserRepository bean when creating UserService.