Swiftorial Logo
Home
Swift Lessons
AI Tools
Learn More
Career
Resources

Spring Framework FAQ: Top Questions

41. What is Spring's @Lazy annotation?

@Lazy is used to delay the initialization of a bean until it is needed, rather than at application startup. It can be applied at the bean definition or injection point level.

📘 Behavior:

  • @Lazy(true): Bean is created only when requested.
  • Can improve startup time by deferring heavy bean initialization.

📥 Example:

@Lazy
@Component
public class HeavyComponent {
  public HeavyComponent() {
    System.out.println("HeavyComponent initialized.");
  }
}

🏆 Expected Output:

"HeavyComponent initialized." is printed only when bean is accessed.

🛠️ Use Cases:

  • Performance optimization in large applications.
  • Optional services or conditional beans.