Skip to content
AITroveRead. Build. Understand.
Make this comfortable

Spring @Lazy singleton: failure moves from context refresh to first use

Last updated: 1 Oct 20264 min read
tutorial
IntermediateBy AITrove Editorial

A lazy singleton is created on first demand instead of during normal eager singleton initialization.

Download Spring source kit

Know when the constructor runs

The checked context starts with no ReportIndex instance. Its first getBean call constructs one; later requests receive that singleton. A second context adds an eager ReportService that requires ReportIndex, and the supposedly lazy index is built during refresh to satisfy that dependency. The annotation alone does not defer every dependency path.

Deferring construction can shorten startup, but it can also postpone an invalid credential, missing file or broken configuration until a user request. For infrastructure needed to serve traffic, startup validation is usually more useful than hiding the failure. Boot configuration validation and readiness handle different parts of that decision.

Avoid confusing identity and timing

A lazy singleton is still one container-managed instance once created; it is not a new object per call. Scopes explains the identity rule. If an eager consumer should hold a proxy instead of forcing the target at startup, inspect lazy injection at the parameter and test the actual call path.

Checked code

Java
@Bean @Lazy ReportIndex reportIndex() {
    constructed.incrementAndGet();
    return new ReportIndex(47);
}
@Bean EagerReportService reportService(ReportIndex index) {
    return new EagerReportService(index);
}

Verification boundary

The Maven source kit passes LifecycleAndMvcDispatchContractTest.lazySingletonWaitsOnlyUntilItIsRequestedOrNeededByEagerBean on its local Spring Boot 4 and Java 21 fixture.

Cost and ownership

Construction work moves to first demand only when no eager bean forces the dependency. That demand can add latency to the first request. The test checks local instance counts; it does not measure real startup savings, request latency or readiness under load.

Common Mistakes

  • Do not assume @Lazy guarantees a dependency stays uncreated at context refresh.
  • Do not hide a required infrastructure failure until live traffic arrives.
  • Do not confuse a lazy singleton with prototype scope.

Read next

Spring @Lazy injection point: defer a dependency behind a proxy, Spring bean scopes: singleton identity is not thread safety, Spring Boot configuration validation: reject an unusable relay before work starts, Spring readiness: report an unavailable dependency without forcing liveness failure.

spring
spring-boot
lazy-singleton-initialization
Storage details