Bird
0
0

Identify the problem in this Spring Boot class using field injection:

medium📝 Debug Q14 of 15
Spring Boot - Inversion of Control and Dependency Injection
Identify the problem in this Spring Boot class using field injection:
public class UserService {
  @Autowired
  private UserRepository userRepository;

  public UserService() {}

  public User findUser(Long id) {
    return userRepository.findById(id).orElse(null);
  }
}
AField injection hides dependencies making testing harder
BConstructor is missing the <code>@Autowired</code> annotation
CThe <code>userRepository</code> field should be static
DThe <code>findUser</code> method should be static
Step-by-Step Solution
Solution:
  1. Step 1: Review injection style

    The class uses field injection with @Autowired on a private field, which hides dependencies.
  2. Step 2: Understand testing impact

    Because dependencies are hidden, it is harder to inject mocks or stubs for unit testing, reducing testability.
  3. Final Answer:

    Field injection hides dependencies making testing harder -> Option A
  4. Quick Check:

    Field injection = hidden dependencies = testing difficulty [OK]
Quick Trick: Field injection hides dependencies, causing test problems [OK]
Common Mistakes:
  • Thinking constructor needs @Autowired always
  • Believing fields must be static for injection
  • Assuming methods must be static for injection

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Spring Boot Quizzes