Sobes.tech
Middle

How do you use dependency injection in your work?

sobes.tech AI

Answer from AI

Dependency Injection (DI) is a pattern that allows dependencies of an object to be passed from outside rather than created internally. In Java, I use DI to enhance modularity, testability, and ease of maintenance.

For example, in the Spring Framework, I declare dependencies as beans, and the Spring container automatically injects them into the necessary classes via constructors or setters. This makes it easier to replace implementations, for instance, when writing unit tests, where mock objects can be substituted.

Example of using DI with a constructor:

@Component
public class UserService {
    private final UserRepository userRepository;

    // Dependency is injected through the constructor
    public UserService(UserRepository userRepository) {
        this.userRepository = userRepository;
    }

    public User findUser(String id) {
        return userRepository.findById(id);
    }
}

This approach promotes inversion of control (IoC), where object creation and binding are controlled by an external container rather than the class itself.

How do you use dependency injection in your work… - sobes.tech