Sub topic 3
Eager and Lazy Initialization
Assume core Java, Spring dependency injection, and basic Spring Boot application setup. A bean’s scope controls how many instances Spring creates and how long each instance lives.
Eager and lazy initialization
Singleton beans are eager by default. Spring creates them while the application context starts, even if no code has requested them yet. This detects configuration errors early, but it can increase startup time.
Use @Lazy to postpone creation until the bean is first requested:
@Component
@Lazy
class ReportGenerator {
ReportGenerator() {
System.out.println("created");
}
}Lazy creation can shorten startup, but an error may appear later during the first request instead of during startup. Use it for expensive or rarely used beans, not as a general performance fix.
flowchart TD
A[Context starts] --> B{Bean is lazy?}
B -- No --> C[Create singleton now]
B -- Yes --> D[Create on first request]caption: Eager and lazy singleton creation alt: A flowchart showing eager beans created at startup and lazy beans created on first request.
Prototype scope
A prototype bean gives a new instance each time the container asks for it:
@Component
@Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE)
class Job {
}Spring creates and initializes prototype instances, but it does not track them for destruction. Therefore, it does not call @PreDestroy, DisposableBean.destroy, or a configured destroy method on them. The code that obtains a prototype must release resources it owns.
Request, session, and application scopes
In a web application:
@RequestScopecreates one bean per HTTP request.@SessionScopecreates one bean per user session.@ApplicationScopecreates one bean for the web application.
These scopes require an active web context. Attempting to resolve a request-scoped bean outside a request usually fails.
Injecting shorter-lived beans into singletons
A singleton cannot safely hold a directly created prototype or request bean. The singleton would keep the same instance after its useful scope ended.
Use ObjectProvider when you need a fresh object on demand:
@Service
class JobRunner {
private final ObjectProvider<Job> jobs;
JobRunner(ObjectProvider<Job> jobs) {
this.jobs = jobs;
}
Job newJob() {
return jobs.getObject();
}
}For web scopes, Spring can inject a scoped proxy. The proxy stays in the singleton, but delegates each call to the current request or session instance.
Custom scopes
Use a custom scope when the built-in lifetimes do not match the application, such as one instance per tenant or workflow. Implement Scope, then register it with the bean factory:
beanFactory.registerScope("tenant", new TenantScope());The scope must define storage, lookup, removal, and destruction-callback behavior. It must also handle cleanup when its context ends.
Lifecycle and SmartLifecycle
SmartLifecycle is useful for components that must start and stop with the context, such as message consumers. Its start() and stop() methods participate in context lifecycle coordination. isAutoStartup() controls automatic startup, and getPhase() controls ordering. Lower phases start first and stop last.
Exercise
Which technique should a singleton use when it needs a new prototype instance for every operation?
Show answer
Inject ObjectProvider<PrototypeType> and call getObject() for each operation.