Sub topic 11
Eager and Lazy Initialization
This chapter covers when the container creates singleton beans: at startup (eager) or on first use (lazy). It assumes you know core Java, @Component, @Autowired, @Configuration and @Bean, and you can run a Spring or Spring Boot application. Earlier chapters covered the singleton scope and the lifecycle callbacks. Here you will see how timing changes where errors appear and when callbacks run.
The default: singletons are created eagerly
A singleton bean is the one shared instance the container keeps for a bean definition. By default, ApplicationContext implementations create all non-lazy singletons during refresh(), after bean definitions are registered and before the context is reported as started. This is called eager initialization.
Eager creation has three practical effects:
- Wiring mistakes surface at startup. A missing dependency, an ambiguous injection point or a failing
@PostConstructstops the application before it serves any traffic. - Slow initialization work is paid once, at startup, instead of by the first user request.
- Memory for every singleton is allocated up front, even for beans that are rarely used.
Prototype beans and web-scoped beans are not part of this pre-instantiation. They are created when something asks for them, as later chapters show.
Lazy initialization
A lazy bean is a singleton that the container creates when it is first requested. The request can come from getBean, from injection into another bean, or from a proxy being used. Until then, only the bean definition exists.
There are three ways to ask for laziness.
On one bean: `@Lazy`
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Component;
@Component
@Lazy
public class ReportGenerator {
public ReportGenerator() {
System.out.println("ReportGenerator created");
}
public String generate() {
return "report";
}
}@Lazy works on a @Component class or on a @Bean method. @Lazy(false) explicitly turns laziness off, which matters when a wider setting makes beans lazy by default.
On a whole configuration: `@Lazy` on `@Configuration`
When you put @Lazy on a @Configuration class, every @Bean method in it is lazy unless the method says @Lazy(false).
Globally: Spring Boot property
spring.main.lazy-initialization=trueSpring Boot then makes all bean definitions lazy, except those marked @Lazy(false). In plain Spring you can get the same effect with setDefaultLazyInit(true) on the bean factory, or default-lazy-init="true" in XML.
Seeing the difference
The program below uses the same ReportGenerator. It prints when the bean is created relative to the context lifecycle.
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
@Configuration
@ComponentScan
class LazyConfig {
}
public class LazyDemo {
public static void main(String[] args) {
try (AnnotationConfigApplicationContext ctx =
new AnnotationConfigApplicationContext(LazyConfig.class)) {
System.out.println("context refreshed");
ctx.getBean(ReportGenerator.class);
System.out.println("bean obtained");
}
}
}With @Lazy on ReportGenerator, the output is:
context refreshed
ReportGenerator created
bean obtainedRemove @Lazy and the constructor line moves in front of context refreshed. The same shift applies to @PostConstruct, afterPropertiesSet and any BeanPostProcessor calls for that bean. Only the timing changes. The order of the callbacks for the bean stays the same.
How `@Lazy` behaves at an injection point
The earlier example works because nothing injects ReportGenerator anywhere. Once another bean depends on a lazy bean, the rule changes.
- If an eager singleton has
ReportGeneratoras a normal constructor parameter, the container must supply an instance to build that singleton. The lazy bean is therefore created during startup, as a consequence of the dependency. Lazy only defers creation when no eager bean pulls it in. - If you put
@Lazyon the injection point itself, the container injects a lazy-resolution proxy instead of the real bean. The real bean is created when a method is first called on the proxy.
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;
@Service
public class ReportService {
private final ReportGenerator generator;
public ReportService(@Lazy ReportGenerator generator) {
this.generator = generator;
}
public String run() {
return generator.generate();
}
}Here ReportService is created at startup, but ReportGenerator is not created until run() calls generate(). The injected object is a proxy, so the class must be proxyable. A class that is final cannot be subclassed by the proxy, so injection fails. If the dependency is an interface, the proxy implements that interface instead.
An alternative with no proxy is ObjectProvider<ReportGenerator>, which you saw in the prototype example. The bean is requested explicitly with getObject() or getIfAvailable(). It makes the delayed lookup visible in the code, and it also handles optional beans.
Trade-offs and failure modes
Lazy initialization is a trade, not a free speedup.
| Aspect | Eager (default) | Lazy |
|---|---|---|
| Startup time | Longer, all singletons built | Shorter, only needed beans built |
| Misconfiguration | Fails at startup | Fails on first use, possibly in production |
| First-request latency | Predictable | The first caller pays for creation |
| Memory | All singletons held | Only used beans held |
| Startup side effects | Run at startup | Delayed or never run |
Watch for these problems:
- Hidden configuration errors. A bean with a wrong property or missing dependency only fails when first used. With global lazy initialization, a whole class of errors moves from deploy time to request time. Run integration tests that touch every bean, or keep critical beans eager.
- Side-effect beans that never start. A bean whose
@PostConstructopens a connection, registers a listener or starts a scheduler does its work only if something creates it. If nothing asks for it, nothing happens. Beans that do work on their own should be marked@Lazy(false). - Slow first request. The first request that touches a heavy lazy bean absorbs its creation time, and the work may happen on a request thread with a timeout.
- Concurrency at first use. The container synchronizes singleton creation, so two threads asking at the same time still get one instance. A slow initialization can block other callers.
- Surprise creation chains. One first call can create a whole graph of lazy beans, each running its own callbacks.
- Destruction. A lazy bean that was never created has nothing to destroy. Its
@PreDestroydoes not run at shutdown.
Choosing between them
- Keep the default for most application code. Early failure is worth a slightly longer startup.
- Use
@Lazyon a specific expensive bean that is rarely needed, such as a large cache or a client for an optional integration. - Consider global lazy initialization for local development or short-lived processes where startup time dominates. Use it in production only if you have tested the paths that were previously checked at startup.
- Use
@Lazyon an injection point, orObjectProvider, to break a startup cycle or to postpone an expensive dependency inside an otherwise eager bean.
Summary of rules
- Non-lazy singletons are created during context refresh.
- A lazy singleton is created at the first request, whether by
getBean, injection into an eager bean, or first use through a lazy proxy. @Lazyon a bean defers creation.@Lazyon an injection point defers resolution with a proxy.- Laziness changes when callbacks run, not their order.
Exercise
A @Lazy bean Cache is injected through a normal constructor parameter into an eager @Service called OrderService. When is Cache created, and what single change would delay creation until OrderService first uses it?
Show answer
Cache is created during startup, because OrderService is an eager singleton and needs an instance of Cache to be constructed. Putting @Lazy on the constructor parameter makes the container inject a proxy, so the real Cache is created when a method is first called on it. Injecting an ObjectProvider<Cache> and calling getObject() when needed also works.
Exercise
You enable spring.main.lazy-initialization=true. A bean QueueListenerStarter subscribes to a message queue in @PostConstruct, and no other bean references it. What happens, and how do you fix it?
Show answer
The bean is never created, so @PostConstruct never runs and the application never subscribes to the queue. Fix it by annotating QueueListenerStarter with @Lazy(false), so it is created during startup despite the global setting.