Bird
0
0

Identify the error in the following Spring Boot code snippet:

medium📝 Debug Q6 of 15
Spring Boot - Inversion of Control and Dependency Injection
Identify the error in the following Spring Boot code snippet:
@Component
public class Service {
  @Autowired
  private Repository repo;

  public Service(Repository repo) {
    this.repo = repo;
  }
}
AField injection and constructor injection used together incorrectly
BMissing @Component annotation on Repository
CConstructor should be private
DNo error, code is correct
Step-by-Step Solution
Solution:
  1. Step 1: Check injection types used

    Field injection (@Autowired on field) and constructor injection (constructor with parameter) are mixed improperly.
  2. Step 2: Understand best practice

    Use either constructor injection or field injection, not both for the same dependency.
  3. Final Answer:

    Field injection and constructor injection used together incorrectly -> Option A
  4. Quick Check:

    Mixing injection types = Error [OK]
Quick Trick: Use one injection style per dependency, preferably constructor [OK]
Common Mistakes:
  • Mixing field and constructor injection
  • Assuming missing annotations cause this error
  • Thinking constructor must be private

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Spring Boot Quizzes