Bird
0
0

Consider a Spring Boot application where a service depends on another service that is lazily initialized. How can you use @Autowired to inject this dependency without causing startup errors?

hard📝 Application Q9 of 15
Spring Boot - Inversion of Control and Dependency Injection
Consider a Spring Boot application where a service depends on another service that is lazily initialized. How can you use @Autowired to inject this dependency without causing startup errors?
AUse @Lazy annotation along with @Autowired on the dependency
BRemove @Autowired and instantiate manually
CMake the dependent service static
DUse @Primary on the dependent service
Step-by-Step Solution
Solution:
  1. Step 1: Understand lazy initialization

    Lazy beans are created only when needed, so injecting them eagerly can cause errors.
  2. Step 2: Use @Lazy with @Autowired

    Adding @Lazy delays injection until the bean is actually used, preventing startup errors.
  3. Final Answer:

    Use @Lazy annotation along with @Autowired on the dependency -> Option A
  4. Quick Check:

    Lazy bean + @Lazy + @Autowired = safe injection [OK]
Quick Trick: Add @Lazy to delay injection of lazy beans [OK]
Common Mistakes:
  • Instantiating beans manually instead of using Spring
  • Making services static to fix injection
  • Using @Primary without addressing lazy init

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Spring Boot Quizzes