Junior — Middle
What is the role and advantages of using dependency injection in the Spring Framework?
sobes.tech AI
Answer from AI
Dependency Injection (DI) in the Spring Framework plays a key role in managing dependencies between application components.
Advantages of using DI:
- Loosening coupling: components do not create their dependencies directly, which simplifies replacement and testing.
- Simplifying testing: mocks or stubs can be easily substituted for real dependencies.
- Managing object lifecycle: the Spring container creates and manages objects, reducing the likelihood of errors.
- Increasing modularity and reusability of code.
Example of using DI with the @Autowired annotation:
@Component
public class UserService {
private final UserRepository userRepository;
@Autowired
public UserService(UserRepository userRepository) {
this.userRepository = userRepository;
}
// service methods
}
Here, Spring automatically injects the required UserRepository bean into UserService.