00:00

Lazy Initialization in Spring

Last updated:

Lazy initialization in Spring means creating a bean the first time it is needed instead of at startup. By default, Spring creates every singleton bean while the application starts, so configuration errors appear immediately and the first request is fast. With @Lazy, or the global spring.main.lazy-initialization property in Spring Boot, you trade that for a quicker start and lower memory use for beans that are rarely used.

This tutorial explains the difference between eager and lazy beans, the four places @Lazy can go and what each does, how global lazy initialization works and how to keep selected beans eager. A runnable example shows exactly when lazy beans are created, and a decision table helps you choose when lazy initialization is worth it.

1. What Is Lazy Initialization?

Initialization here means the whole bean lifecycle up to "ready": calling the constructor, injecting dependencies and running callbacks such as @PostConstruct. Lazy initialization postpones all of that until something first asks for the bean, either by injecting it into a bean that is being created or by looking it up.

Analogy: A restaurant can cook every dish on the menu before opening (eager), or cook each dish when the first customer orders it (lazy). Cooking ahead makes opening slower but serving fast, and you find out at once if an ingredient is missing. Cooking on demand opens the doors sooner, but the first customer waits and a missing ingredient is discovered in front of a guest.

2. Eager vs Lazy Beans

AspectEager (default)Lazy
CreatedDuring startup, in the context refreshOn first use
Configuration errorsFail at startupFail at first use, possibly in production traffic
Startup timeLongerShorter
First requestFastSlower while beans are created
Memory at startupAll beansOnly beans that were used
Applies toSingletonsSingletons (prototype beans are always created on demand)
When eager and lazy beans are createdOn a timeline from application start to the first request, eager beans such as the ProductCatalog are created during startup, before the application reports ready. A lazy ReportEngine bean is not created at startup; it is created when the first request that needs it arrives, which makes that first request slower. A lazy bean that is never used is never created. start ready first report request Startup (context refresh) eager beans created: ProductCatalog, controllers, repositories First request to /api/reports lazy ReportEngine created now, so this request is slower the lazy bean is not created during startup
Eager beans are created before the application is ready; lazy beans are created by the first request that needs them.

3. Using the @Lazy Annotation

@Lazy (from org.springframework.context.annotation) can be placed in four places:

PlacementEffect
On a @Component classThat bean is created on first use
On a @Bean methodThat bean is created on first use
On a @Configuration classEvery @Bean in that class is lazy
On an injection point (constructor parameter, field, setter)A lazy proxy is injected; the target is resolved on the first method call
ReportEngine.java
@Component
@Lazy
public class ReportEngine {
    // created only when something first needs it
}

A lazy bean is still created at startup if an eager bean injects it directly, because the eager bean needs a real object for its constructor. Making a bean lazy therefore only helps if its users are lazy too, or if they inject it lazily as shown next.

4. @Lazy on Injection Points: Lazy Proxies

With @Lazy on a constructor parameter, Spring does not resolve the dependency at all during construction. It injects a proxy of the same type, and the proxy looks up the real bean on its first method call.

ReportController.java
public ReportController(@Lazy ReportEngine engine) {
    this.engine = engine;   // a proxy; ReportEngine itself is not created yet
}

This is useful when an eager bean depends on an expensive bean it rarely uses, and it is also how @Lazy can break a circular dependency as a temporary workaround. If the target bean turns out not to exist, the error appears on that first call rather than at startup.

5. Global Lazy Initialization in Spring Boot

Spring Boot can make every bean lazy with one property:

application.properties
spring.main.lazy-initialization=true

The same can be done in code with SpringApplication.setLazyInitialization(true) or SpringApplicationBuilder.lazyInitialization(true). Behind the scenes, a LazyInitializationBeanFactoryPostProcessor marks each bean definition as lazy before any bean is created.

Some beans still start eagerly, because Spring needs them to run the application: infrastructure such as bean post-processors, the embedded web server, and beans that implement SmartInitializingSingleton. In a web application, many web-related beans are created on the first HTTP request instead of at startup.

6. Keeping Selected Beans Eager

With global lazy initialization on, mark beans that must run at startup with @Lazy(false):

CatalogCacheWarmer.java
@Component
@Lazy(false)   // must load the cache at startup even when everything else is lazy
public class CatalogCacheWarmer {
    // ...
}

For beans you cannot annotate, such as classes from a library, register a LazyInitializationExcludeFilter bean:

LazyConfig.java
@Configuration
class LazyConfig {

    @Bean
    static LazyInitializationExcludeFilter keepSchedulersEager() {
        return LazyInitializationExcludeFilter.forBeanTypes(ThreadPoolTaskScheduler.class);
    }
}

Beans that do work in the background, such as scheduled tasks and message listeners that are not managed by a lifecycle container, are prime candidates: if they are lazy and nobody injects them, they never start.

7. A Complete Example: A Heavy Report Engine

A shop has a report engine that loads large templates at creation, and a product catalog used on every request. The report engine is used rarely, so it is lazy.

7.1 The Beans

ProductCatalog.java
package com.javabytechie.shop.catalog;

import jakarta.annotation.PostConstruct;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

@Component
public class ProductCatalog {

    private static final Logger log = LoggerFactory.getLogger(ProductCatalog.class);

    @PostConstruct
    void load() {
        log.info("ProductCatalog created (eager)");
    }

    public int size() {
        return 2;
    }
}
ReportEngine.java
package com.javabytechie.shop.report;

import jakarta.annotation.PostConstruct;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Component;

@Component
@Lazy
public class ReportEngine {

    private static final Logger log = LoggerFactory.getLogger(ReportEngine.class);

    @PostConstruct
    void loadTemplates() throws InterruptedException {
        log.info("ReportEngine loading templates...");
        Thread.sleep(800);   // stands in for loading large templates
        log.info("ReportEngine ready (lazy)");
    }

    public String salesSummary(String month) {
        return "Sales summary for " + month + ": 1,284 orders";
    }
}

7.2 The Controller with a Lazy Injection Point

ReportController.java
package com.javabytechie.shop.report;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Lazy;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/api/reports")
public class ReportController {

    private static final Logger log = LoggerFactory.getLogger(ReportController.class);
    private final ReportEngine engine;

    public ReportController(@Lazy ReportEngine engine) {
        this.engine = engine;
        log.info("ReportController created with {}", engine.getClass().getSimpleName());
    }

    @GetMapping("/sales/{month}")
    public String sales(@PathVariable String month) {
        return engine.salesSummary(month);
    }
}

Without @Lazy on the parameter, the eager controller would force ReportEngine to be created at startup, and the @Lazy on the class would have no effect.

7.3 Run It

Terminal
./mvnw spring-boot:run
curl localhost:8080/api/reports/sales/2026-11
curl localhost:8080/api/reports/sales/2026-12
Console
ProductCatalog created (eager)
ReportController created with ReportEngine$$SpringCGLIB$$0
Started ShopApplication in 1.15 seconds (process running for 1.40)
ReportEngine loading templates...
ReportEngine ready (lazy)

The controller received a CGLIB proxy at startup, and ReportEngine was created only by the first request, which took about 0.8 seconds longer. The second request reused the same instance and logged nothing. The exact proxy class name can differ between versions.

8. Benefits and Drawbacks

BenefitsDrawbacks
Faster startup, especially with many rarely used beansConfiguration errors surface at runtime instead of at startup
Lower memory if some beans are never usedThe first request that needs a bean is slower
Quicker restarts during development and in testsMemory sizing is harder: peak use comes later, under load
Can unblock a circular dependency temporarilyLazy proxies add indirection and can hide design problems

The Spring Boot documentation recommends tuning the JVM heap before enabling lazy initialization, because the application must still have enough memory for all its beans once they are created.

9. When to Use Lazy Initialization

Good usePoor use
One expensive bean used by a rare feature (@Lazy on it and its injection points)Global lazy initialization in production to "fix" slow startup
Global lazy initialization in local development for faster restartsBeans that must start background work, such as schedulers
Command-line tools where each run uses only a few beansLatency-sensitive services where the first request must be fast
Large integration test suites, if a separate test still loads everything eagerlyThe only context-loading test, which then misses broken beans

To make production startup faster, measure first and fix the slow beans; see the application startup process.

10. Best Practices

  • Keep the default eager behavior in production so broken configuration fails at startup.
  • Make individual expensive, rarely used beans lazy rather than the whole application.
  • Add @Lazy to the injection points too, or the bean is still created by its eager users.
  • Mark startup-critical beans @Lazy(false) when global lazy initialization is on.
  • Keep one eager context test so every bean is created at least once in CI.
  • Size the heap for all beans, not just those created at startup.

11. Summary

Lazy initialization in Spring delays creating a bean until it is first needed. @Lazy on a class or @Bean method makes one bean lazy, on a @Configuration class makes all its beans lazy, and on an injection point injects a proxy that resolves the bean on first use. Spring Boot's spring.main.lazy-initialization=true makes every bean lazy, with @Lazy(false) and LazyInitializationExcludeFilter to keep selected beans eager. Use it selectively for expensive, rarely used beans or for faster development restarts, and keep production eager so configuration errors appear at startup, not in front of users.

12. References