Sobes.tech
Junior — Middle

What methods are used in Spring to implement dependency injection and which of them are considered correct?

sobes.tech AI

Answer from AI

In Spring, dependency injection (DI) is implemented in three main ways:

  1. Through constructor — dependencies are passed to the class via its constructor. This is considered the most correct and recommended method, as it ensures immutability of dependencies and facilitates testing.

  2. Through setters — dependencies are set via setter methods after the object is created. Suitable when dependencies are optional or can change.

  3. Through field injection — dependencies are injected directly into the class fields using the @Autowired annotation. This method is less preferred, as it complicates testing and breaks encapsulation.

Example of constructor injection:

@Component
public class UserService {
    private final UserRepository userRepository;

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

Thus, it is recommended to use constructor-based dependency injection to improve reliability and ease of testing.