Video in progress

Junior 🌱 Spring

What changes when you put @Lazy on a bean?

Singleton beans are normally created at startup, but a @Lazy one is created the first time it's needed. If you put it on an injection point, Spring immediately hands over a proxy instead of the real bean.

📖 Answer

@Service
@Lazy
class PdfRenderer {          // loads a heavy library
    PdfRenderer() { /* 3 seconds */ }
}

@Service
class InvoiceService {
    private final PdfRenderer renderer;

    InvoiceService(@Lazy PdfRenderer renderer) {  // a proxy arrives
        this.renderer = renderer;
    }
}

You can put it in two places:

  • on the class or a @Bean: the bean is deferred, but if someone injects it normally, it's still created at startup;
  • on the injection point: a proxy arrives, and the real bean is created on the first method call. That's why the two are often used together.

The global variant: spring.main.lazy-initialization=true defers every bean.

It has a cost: a configuration error (say, a missing dependency) shows up on the first request, not at startup. The first user gets a slow response. That's why global lazy is rarely enabled in prod; it's mostly used locally and in tests to speed up startup.