Bird
0
0

What is wrong with this Spring Boot code snippet that uses IoC?

medium📝 Debug Q14 of 15
Spring Boot - Inversion of Control and Dependency Injection
What is wrong with this Spring Boot code snippet that uses IoC?
@Component
public class Service {
  private Repository repo;

  public Service() {
    repo = new Repository();
  }
}
ANo error, this is correct IoC usage.
BService class must not have a constructor.
C@Component annotation is missing on Repository class.
DRepository should be injected by Spring, not created with new.
Step-by-Step Solution
Solution:
  1. Step 1: Identify manual object creation

    The Service class creates Repository with new, bypassing Spring IoC container.
  2. Step 2: Explain correct IoC practice

    Spring should inject Repository using @Autowired to manage dependencies and lifecycle.
  3. Final Answer:

    Repository should be injected by Spring, not created with new. -> Option D
  4. Quick Check:

    Manual new breaks IoC, use injection [OK]
Quick Trick: Avoid new; let Spring inject dependencies with @Autowired [OK]
Common Mistakes:
  • Thinking constructor is not allowed in @Component
  • Assuming missing annotation on Repository is the main issue
  • Believing manual new is correct IoC usage

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Spring Boot Quizzes