Sub topic 9
Bean scopes: singleton, prototype and web scopes
This chapter assumes you can define beans with @Component or @Bean and inject them through constructors. A bean's scope controls how many instances the container creates and how long each one lives.
Singleton: the default
Unless you say otherwise, a bean is a singleton. The ApplicationContext creates one instance per bean definition and returns that same instance to every injection point and every getBean call.
"Singleton" here means one instance per container, not one per JVM as in the classic design pattern. Two contexts in one JVM each hold their own instance.
Because many threads share a singleton, it should be stateless or its state must be thread-safe. A singleton with a mutable field such as a List of the current user's items is a common source of bugs that only appear under load.
Prototype: a new instance each time
A prototype bean is created every time the container is asked for it. This happens on each getBean call and each time the bean is injected into another bean.
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;
@Component
@Scope("prototype")
public class ReportBuilder {
}Use prototype for objects that hold per-use state, such as a builder that accumulates data.
The lifecycle differs from singletons. Spring creates and wires a prototype, then hands it over and stops tracking it. @PreDestroy is never called on prototypes, so you must release any resources yourself.
The prototype-in-singleton trap
Injection happens once, when the singleton is created. If a singleton receives a prototype through its constructor, it gets one instance and keeps it forever. The prototype scope then has no effect.
To get a fresh instance on each use, inject an ObjectProvider and ask it when you need one:
import org.springframework.beans.factory.ObjectProvider;
import org.springframework.stereotype.Service;
@Service
public class ReportService {
private final ObjectProvider<ReportBuilder> builders;
public ReportService(ObjectProvider<ReportBuilder> builders) {
this.builders = builders;
}
public ReportBuilder newBuilder() {
return builders.getObject();
}
}Each call to newBuilder() now returns a new ReportBuilder.
Web scopes
In a web application, the container also supports scopes tied to HTTP lifetimes. They are available only in a web-aware context, such as a Spring MVC or Spring Boot web application.
| Scope | Annotation | Lifetime |
|---|---|---|
| request | `@RequestScope` | One HTTP request |
| session | `@SessionScope` | One HTTP session |
| application | `@ApplicationScope` | The servlet context |
import org.springframework.stereotype.Component;
import org.springframework.web.context.annotation.RequestScope;
@Component
@RequestScope
public class RequestContext {
private String correlationId;
public String getCorrelationId() {
return correlationId;
}
public void setCorrelationId(String correlationId) {
this.correlationId = correlationId;
}
}You can inject RequestContext into a singleton controller. These annotations default to a scoped proxy. The singleton receives a proxy that forwards each call to the instance belonging to the current request. Without a proxy you would hit the same trap as above, and creation would fail at startup because no request exists yet.
Common errors
- Storing per-request data in a singleton field, which leaks data between users.
- Expecting
@PreDestroyto run on a prototype. - Injecting a prototype directly into a singleton and expecting new instances.
- Using a web scope outside a web context, which throws an error such as "No scope registered for scope name 'request'".
Exercise
A singleton OrderService has a constructor parameter of type ReportBuilder, which is a prototype bean. After 100 calls to OrderService, how many ReportBuilder instances were created by injection, and how would you change the code to get a new one per call?
Show answer
One instance, because the constructor runs once. Inject ObjectProvider<ReportBuilder> and call getObject() for each use.