Ever enabled spring.main.lazy-initialization=true to speed up startup, only to hit an error on the first request in production? And when you add @Lazy, it’s often unclear what actually gets deferred, or when to use it instead of the global setting.

In this article, we’ll add logging to constructors so we can see when each Bean is created. Along the way, we’ll compare the different places you can put @Lazy, look at the global setting and how to exclude Beans from it, and cover the pitfalls that can hurt you in production. The examples assume Spring Boot 3.5.x and Java 21. @Slf4j in the code is a Lombok annotation, so if you don’t use Lombok, replace it with LoggerFactory.getLogger. In Spring Boot 4.x, the property and exclude filters work the same way, but auto-configuration has been reorganized, so check the exact behavior in the version you use.

Note that JPA’s FetchType.LAZY is a separate mechanism for lazily loading entity associations. That topic is covered in the LazyInitializationException article.

What Is Lazy Initialization?

By default, Spring Boot creates all singleton Beans at startup, when the ApplicationContext is refreshed. With lazy initialization enabled, a Bean isn’t created until something calls getBean for it or it is injected into another Bean.

The quickest way to check is to log from the constructor.

@Slf4j
@Component
public class ReportService {
    public ReportService() {
        log.info("ReportService created");
    }
}

During a normal startup, this log line appears before Started DemoApplication in ... seconds. If the Bean is lazy, it appears after the Started line, when the Bean is first used. @PostConstruct is deferred along with Bean creation. For the full picture, see the Bean lifecycle article.

Where You Put @Lazy Changes Its Effect

Let’s start with @Lazy alone and leave the global setting off. There are four main places you can put it.

On a Class or an @Bean Method

The most common approach is to annotate the class. It works the same way with @Service and @Repository. For @Component itself, see the @Component article.

@Lazy
@Service
public class ReportService { /* ... */ }

For Beans defined with @Bean, such as external API clients, annotating the method makes only that Bean lazy.

@Configuration
public class ClientConfig {
    @Bean
    @Lazy
    public HeavyApiClient heavyApiClient() {
        return new HeavyApiClient(); // 初期化が重い想定
    }
}

On an @Configuration Class

When you put it on an @Configuration class, every @Bean in that class becomes lazy. If you want some of them created at startup, override with @Lazy(false).

@Lazy
@Configuration
public class ReportConfig {
    @Bean
    public PdfRenderer pdfRenderer() { return new PdfRenderer(); } // 遅延される

    @Bean
    @Lazy(false)
    public TemplateLoader templateLoader() { return new TemplateLoader(); } // 起動時に生成
}

On an Injection Point

When you put it on a constructor parameter or field where a dependency is injected, Spring injects a proxy instead of the real object. In this example, ReportService also has @Lazy on its class.

@Slf4j
@Service
public class OrderService {
    private final ReportService reportService; // ReportServiceはクラスに@Lazyあり

    public OrderService(@Lazy ReportService reportService) {
        this.reportService = reportService;
        log.info("injected: {}", reportService.getClass().getSimpleName());
    }

    public void finish() {
        reportService.generate(); // ここで初めて ReportService created が出る
    }
}

The startup log shows the proxy’s class name, such as injected: ReportService$$SpringCGLIB$$0 (this is the naming used in Spring Framework 6.x). Keep in mind that CGLIB can’t proxy final classes or classes without an accessible constructor.

The key point is that @Lazy on an injection point only defers resolving the dependency. If ReportService is a regular singleton, it’s already created at startup, and the proxy just delegates to it. For how the injection styles themselves differ, see the comparison of the three dependency injection styles.

Where you put itWhat gets deferredWhen the actual instance is created
Class / @Bean methodThat BeanWhen first requested or injected
@ConfigurationAll @Beans in itWhen first requested or injected
Injection pointDependency resolution (creation is deferred only if the target Bean is itself lazy)When a method is first called

@Lazy Is Set, but the Bean Is Still Created at Startup

This one catches a lot of people. Even if ReportService has @Lazy, a non-lazy OrderService that takes it as a regular constructor parameter forces ReportService to be created when OrderService is created. In the logs, you see “created” at startup even though the class has @Lazy.

To fix it, either add @Lazy on the injecting side as well (as shown in the previous section), or use ObjectProvider to get the Bean only when you need it.

@Service
public class OrderService {
    private final ObjectProvider<ReportService> reportService;

    public OrderService(ObjectProvider<ReportService> reportService) {
        this.reportService = reportService;
    }

    public void finish() {
        reportService.getObject().generate();
    }
}

@Scope(proxyMode = ...) also uses proxies, but it’s a separate mechanism for scopes. If you’re curious, see the Bean scope article.

Making the Whole Application Lazy with spring.main.lazy-initialization

Since Spring Boot 2.2, a single property makes every Bean definition in the application lazy.

spring.main.lazy-initialization=true

To set it in code, use either of the following.

// SpringApplicationBuilderを使う場合
new SpringApplicationBuilder(DemoApplication.class)
        .lazyInitialization(true)
        .run(args);

// SpringApplicationを直接使う場合
SpringApplication app = new SpringApplication(DemoApplication.class);
app.setLazyInitialization(true);
app.run(args);

If you only want it during local development, put it in application-dev.properties and start the app with the dev profile. For how to switch profiles, see the profiles article.

A simple way to think about it: with @Lazy on individual Beans, you choose what to defer. With the global setting, everything is deferred and you choose what to exclude.

Excluding Specific Beans from Lazy Initialization

There are two ways to exclude Beans when you use the global setting. For your own classes, just add @Lazy(false).

For Beans you can’t annotate, such as those registered by libraries, register a LazyInitializationExcludeFilter as a Bean and specify them by type (Spring Boot 2.2+).

@Configuration
public class LazyExcludeConfig {
    @Bean
    static LazyInitializationExcludeFilter eagerBeans() {
        // 生成時に認証情報を検証するSDKクライアントを想定
        return LazyInitializationExcludeFilter.forBeanTypes(PaymentGatewayClient.class);
    }
}

If you exclude clients that validate their connection or configuration in the constructor, those mistakes show up at startup. Excluding DataSource, however, doesn’t do this. HikariCP doesn’t start its pool until the first getConnection call, so connection configuration errors still won’t appear at startup. This is easy to get wrong.

Measuring Startup Time

To see the effect, it helps to add a test Bean that deliberately waits in its constructor.

@Component
public class SlowStartupBean {
    public SlowStartupBean() throws InterruptedException {
        Thread.sleep(2000); // 重い初期化の代わり
    }

    public String hello() { return "hello"; }
}

Start the app about five times with the setting enabled and five times with it disabled, and average the Started DemoApplication in X seconds values from the logs. Also measure the first request to an endpoint that uses this Bean.

java -jar target/demo.jar --spring.main.lazy-initialization=true
# 別ターミナルで初回リクエストの所要時間を測る
curl -o /dev/null -s -w "%{time_total}\n" http://localhost:8080/hello

In theory, the Started time drops by the length of the wait, and that time moves to the first request. Lazy initialization only saves the time spent creating your own Beans and other heavy Beans. Auto-configuration evaluation, class loading and embedded Tomcat startup still happen at startup. The actual difference depends heavily on your machine and setup, so this article doesn’t quote general numbers. Measure it in your own application. Other techniques such as CDS and AOT are covered in the startup performance article.

Pitfalls of Lazy Initialization

Configuration Errors Stay Hidden Until the First Access

Even if the property for @Value("${payment.api-key}") is missing, the application starts successfully. The BeanCreationException only happens on the first request that uses that Bean. To validate configuration values at startup, use the approach in the @ConfigurationProperties validation article. The same applies to missing dependency Beans. For how to track down the cause, see the NoSuchBeanDefinitionException troubleshooting article. If the health check doesn’t touch the Bean, your post-deployment checks won’t catch the problem either.

A good safeguard is to keep one context-load test in CI that runs with lazy initialization turned off.

@SpringBootTest(properties = "spring.main.lazy-initialization=false")
class EagerContextLoadTest {
    @Test
    void contextLoads() {
    }
}

For how to read startup errors, see the startup failure troubleshooting article.

The First Request Is Slower

On the first request, the whole chain of Beans (Controller, Service, Repository) is created at once, which adds latency. This is a separate problem from slowness caused by JIT warm-up, and the two can stack.

Also, DispatcherServlet is initialized on the first request by default, whether or not lazy initialization is enabled (spring.mvc.servlet.load-on-startup=-1). With global lazy initialization, creating your business Beans adds to that cost. Either send warm-up requests before the app reports ready, or exclude the Beans on critical paths.

Beans with Startup Logic Never Run

Under global lazy initialization, a Bean that nothing injects is never created. A Bean that warms a cache in @PostConstruct will silently do nothing.

@Lazy(false)
@Component
public class CacheWarmer {
    @PostConstruct
    void warmUp() { /* キャッシュ読み込み */ }
}

ApplicationRunner and CommandLineRunner Beans are still retrieved and run at startup even with lazy initialization enabled, so putting startup logic there is another option.

For @Scheduled, if @EnableScheduling is present, auto-configuration in Spring Boot 2.4+ registers a ScheduledBeanLazyInitializationExcludeFilter, which excludes Beans with @Scheduled methods from lazy initialization. So on 3.5.x, scheduled tasks still run with global lazy initialization enabled. If auto-configuration doesn’t apply in your setup, add @Lazy(false). @EventListener still works because the Bean is created when the event fires, but it’s created later than it otherwise would be. For @Scheduled basics, see the @Scheduled article.

Heap Size Estimates Are Off

The official documentation warns about this one. Right after startup, not all Beans exist yet, so memory usage looks lower than it really is. If you use lazy initialization in production, the docs recommend sizing the heap for the state where every Bean has been created.

Side Note: Circular References and @Lazy

When constructor injection causes a circular reference, adding @Lazy to one of the injection points breaks the cycle with a proxy. However, this is only a stopgap. The proper fix is to rethink the design, for example by splitting responsibilities.

Summary

Lazy initialization doesn’t reduce the work. It just moves startup work to later, so decide based on where that work will cause the least trouble.

ScenarioRecommendation
Local developmentFine to enable with the dev profile
TestsEnable if speed matters, but keep one eager context-load test
ProductionGenerally disable. If needed, use @Lazy on individual heavy Beans
CLIs or serverless apps with many unused BeansWorth considering

If you do enable it, take care of three things: exclude Beans that run startup logic or validate on creation, run an eager context-load test in CI, and size the heap for a fully initialized application.


Notes:

  • I left the code examples exactly as they were, so the Japanese comments in them (for example // 初期化が重い想定) are still in Japanese. If you want English comments in the code too, I can translate those.
  • All internal links still point to /ja/blog/.... If English versions exist at /en/blog/... with the same slugs, you may want to point the links there.