Bird
0
0

What is wrong with this Spring Boot class using field injection?

medium📝 Debug Q7 of 15
Spring Boot - Inversion of Control and Dependency Injection
What is wrong with this Spring Boot class using field injection?
@Component
public class EmailService {
  @Autowired
  private SmtpClient smtpClient;

  public void sendEmail() {
    smtpClient.connect();
  }

  public EmailService(SmtpClient smtpClient) {
    this.smtpClient = smtpClient;
  }
}
AField injection and constructor injection conflict causing unpredictable behavior
BConstructor injection overrides field injection correctly
CNo issues, this is a recommended pattern
DMissing @Autowired on constructor causes injection failure
Step-by-Step Solution
Solution:
  1. Step 1: Identify injection types used

    The class uses both field injection (@Autowired on field) and constructor injection (constructor with parameter).
  2. Step 2: Understand conflict

    Mixing field and constructor injection can cause confusion and unpredictable dependency assignment.
  3. Final Answer:

    Field injection and constructor injection conflict causing unpredictable behavior -> Option A
  4. Quick Check:

    Mixed injection types cause conflicts = A [OK]
Quick Trick: Avoid mixing field and constructor injection in same class [OK]
Common Mistakes:
  • Assuming constructor injection overrides field injection safely
  • Thinking this pattern is recommended
  • Believing missing @Autowired on constructor is the main issue

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Spring Boot Quizzes