Lazy Initialization in Spring
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.
2. Eager vs Lazy Beans
| Aspect | Eager (default) | Lazy |
|---|---|---|
| Created | During startup, in the context refresh | On first use |
| Configuration errors | Fail at startup | Fail at first use, possibly in production traffic |
| Startup time | Longer | Shorter |
| First request | Fast | Slower while beans are created |
| Memory at startup | All beans | Only beans that were used |
| Applies to | Singletons | Singletons (prototype beans are always created on demand) |
3. Using the @Lazy Annotation
@Lazy (from org.springframework.context.annotation) can be placed in four places:
| Placement | Effect |
|---|---|
On a @Component class | That bean is created on first use |
On a @Bean method | That bean is created on first use |
On a @Configuration class | Every @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 |
@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.
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:
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):
@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:
@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
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;
}
}
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
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
./mvnw spring-boot:run
curl localhost:8080/api/reports/sales/2026-11
curl localhost:8080/api/reports/sales/2026-12
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
| Benefits | Drawbacks |
|---|---|
| Faster startup, especially with many rarely used beans | Configuration errors surface at runtime instead of at startup |
| Lower memory if some beans are never used | The first request that needs a bean is slower |
| Quicker restarts during development and in tests | Memory sizing is harder: peak use comes later, under load |
| Can unblock a circular dependency temporarily | Lazy 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 use | Poor 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 restarts | Beans that must start background work, such as schedulers |
| Command-line tools where each run uses only a few beans | Latency-sensitive services where the first request must be fast |
| Large integration test suites, if a separate test still loads everything eagerly | The 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
@Lazyto 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
Lazy Initialization in Spring Interview Questions and Answers
Common interview questions on Lazy Initialization in Spring, from basic to scenario-based, with short answers you can explain in your own words.
Q. What is the difference between @Lazy on a class and @Lazy on an injection point?
Answer: On a class or @Bean method, @Lazy changes when that bean is created: on first use instead of at startup. On an injection point, it changes what the consumer receives: a proxy that resolves the real bean on its first method call. Without the injection-point annotation, an eager consumer still forces a lazy bean to be created at startup.
Q. What does spring.main.lazy-initialization=true change, and what are the risks?
Answer: It marks every bean definition as lazy, so beans are created when first needed, which shortens startup and can reduce memory. The risks: misconfigured beans fail at the first request instead of at startup, first requests are slower, memory needs show up later under load, and background beans nobody injects may never start. Infrastructure beans such as post-processors and the web server are still created eagerly.
Q. With global lazy initialization enabled, how do you keep certain beans eager?
Answer: Annotate the class or @Bean method with @Lazy(false). For classes you cannot annotate, declare a LazyInitializationExcludeFilter bean, for example LazyInitializationExcludeFilter.forBeanTypes(SomeLibraryBean.class), preferably from a static method because it is used while bean definitions are processed.
Q. Are prototype beans affected by lazy initialization?
Answer: No. Prototype beans are never created at startup; a new instance is created every time one is requested or injected, so they are effectively always lazy. Lazy initialization only changes the behavior of singletons. Note, however, that injecting a prototype into an eager singleton creates one prototype instance at startup, as part of creating that singleton.
Q. A teammate enables lazy initialization in production to cut startup from 20 to 8 seconds. What would you check before agreeing?
Answer: That every bean is still created at least once in an eager test, so configuration errors are not discovered in production; that background beans such as schedulers and listeners still start; that first-request latency is acceptable, or that readiness waits for warm-up; and that the heap is sized for all beans. Then measure with the startup timeline: often a few slow beans explain most of the 20 seconds and can be fixed directly.