Sobes.tech
Middle+

How is dependency injection recommended in Spring?

sobes.tech AI

Answer from AI

In Spring, it is recommended to use:

  • Constructor injection — the preferred method, especially for mandatory dependencies. It allows making fields final, improves testability, and makes dependencies explicit.

  • Setters or fields with the @Autowired annotation — used for optional dependencies or when constructor injection is inconvenient.

Example of constructor injection:

@Component
public class UserService {
    private final UserRepository userRepository;

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

    // methods
}

Spring will automatically inject the required UserRepository bean when creating UserService. This approach promotes immutability and makes the class dependencies clearer.