Sub topic 9
Bean scopes: singleton, prototype and web scopes
This chapter assumes you know how to define beans with @Component and @Bean, and how constructor injection works. It also assumes you have used an ApplicationContext to look up a bean. If those are new, review the earlier chapters first.
What a scope controls
A bean definition is a recipe. The scope decides how many objects the container builds from that recipe and how long each one lives. When you ask the container for a bean, or when it injects one, the scope determines whether you receive a shared instance or a fresh one.
Spring ships with these scopes:
| Scope | Instances per recipe | Available in |
|---|---|---|
| `singleton` | One per container | Every context (default) |
| `prototype` | A new one on every request to the container | Every context |
| `request` | One per HTTP request | Web-aware contexts |
| `session` | One per HTTP session | Web-aware contexts |
| `application` | One per `ServletContext` | Web-aware contexts |
| `websocket` | One per WebSocket session | Web-aware contexts |
If you do not declare a scope, you get singleton.
Singleton: the default
A singleton bean is created once, usually when the context starts, and every injection point receives the same object. "Singleton" here means one instance per container and per bean definition. It does not mean one instance per JVM as in the classic design pattern. Two contexts in the same JVM each hold their own instance. Two bean definitions of the same class in one context produce two instances.
Because many threads share one object, a singleton must be safe for concurrent use. The usual rule is to keep singleton beans stateless, or to keep only immutable state such as injected dependencies.
import org.springframework.stereotype.Component;
@Component
public class VisitCounter {
private int visits; // shared mutable state in a singleton
public int next() {
return ++visits; // not thread-safe
}
}The class above has a data race when two requests call next() at once. Either remove the field, use AtomicInteger, or move the state out of the bean into a database or cache.
import java.util.concurrent.atomic.AtomicInteger;
import org.springframework.stereotype.Component;
@Component
public class SafeVisitCounter {
private final AtomicInteger visits = new AtomicInteger();
public int next() {
return visits.incrementAndGet();
}
}Singletons are created eagerly by default. A misconfigured singleton therefore fails at startup, not on first use. You can defer creation with @Lazy, at the cost of moving that failure to runtime.
Prototype: a new instance per request
A prototype bean is built each time something asks the container for it. You declare it with @Scope("prototype"). Use it for objects that hold per-use state, such as a builder or a short-lived calculation.
import org.springframework.beans.factory.config.ConfigurableBeanFactory;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;
@Component
@Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE)
public class ReportBuilder {
private final StringBuilder text = new StringBuilder();
public ReportBuilder line(String value) {
text.append(value).append('\n');
return this;
}
public String build() {
return text.toString();
}
}The same scope on a @Bean method looks like this:
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Scope;
@Configuration
public class BuilderConfig {
@Bean
@Scope("prototype")
public ReportBuilder reportBuilder() {
return new ReportBuilder();
}
}Two points about prototypes matter in practice:
- The container creates, wires and hands over the instance, then forgets it. It does not call
@PreDestroyor any other destruction callback on prototypes. Your code must release any resources they hold. - Each prototype is created when it is requested, so a prototype injected into a constructor is created once, at that moment.
The singleton-holds-prototype problem
The second point above causes the most common scope bug. Suppose a singleton needs a fresh ReportBuilder for each call:
import org.springframework.stereotype.Service;
@Service
public class ReportService {
private final ReportBuilder builder;
public ReportService(ReportBuilder builder) {
this.builder = builder; // injected once, reused forever
}
public String render(String title) {
return builder.line(title).build(); // output accumulates across calls
}
}ReportService is a singleton, so its constructor runs once. The injected ReportBuilder is a single object kept for the life of the service. The prototype scope has no effect, and every call appends to the same buffer.
The diagram shows what happens when the dependency is injected directly and when it is requested per call.
Fix 1: ObjectProvider
ObjectProvider<T> is a Spring type that defers the lookup. Inject the provider, then call getObject() whenever you need an instance.
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 String render(String title) {
ReportBuilder builder = builders.getObject(); // fresh each call
return builder.line(title).build();
}
}This is explicit and easy to test, because a test can supply its own provider. The cost is that your class now depends on a Spring type. jakarta.inject.Provider<T> works the same way and avoids that dependency if it is on the classpath.
Fix 2: a scoped proxy
You can ask Spring to inject a proxy instead of the real object. The proxy is a stand-in that looks up the target bean on every method call.
import org.springframework.context.annotation.Scope;
import org.springframework.context.annotation.ScopedProxyMode;
import org.springframework.stereotype.Component;
@Component
@Scope(value = "prototype", proxyMode = ScopedProxyMode.TARGET_CLASS)
public class ProxiedReportBuilder {
// ...
}With a proxy, each method call on the injected object may reach a different target instance. For a stateful prototype like a builder, that breaks chaining, because line() and build() would act on two different objects. Scoped proxies suit web scopes far better than prototypes.
Fix 3: lookup methods
A @Lookup method on a Spring-managed class is overridden by Spring so that it calls the container. It works but relies on subclass generation, so the class and method cannot be final or private. Most teams prefer ObjectProvider.
Web scopes
The web scopes exist only in a web-aware context, such as a Spring MVC or Spring Boot web application. In a plain AnnotationConfigApplicationContext the container throws an IllegalStateException or a "No scope registered for scope name 'request'" error when it meets one.
request: one instance per HTTP request. Good for data that belongs to one call, such as a request correlation ID.session: one instance per user HTTP session. Good for small per-user state such as a shopping cart. Keep it small and serializable, because sessions may be replicated or persisted.application: one instance perServletContext. It resembles a singleton but is shared across all Spring contexts inside the same web application.websocket: one instance per WebSocket session.
Spring provides shortcut annotations for the common ones: @RequestScope, @SessionScope and @ApplicationScope. They set the scope and also enable a scoped proxy by default.
import org.springframework.web.context.annotation.RequestScope;
import org.springframework.stereotype.Component;
import java.util.UUID;
@Component
@RequestScope
public class RequestContext {
private final String requestId = UUID.randomUUID().toString();
public String requestId() {
return requestId;
}
}The proxy matters here. A controller or service is a singleton and is built at startup, when no request exists. If it received the real RequestContext, there would be nothing to inject. The proxy is injected instead, and each call on it finds the RequestContext of the current request.
import org.springframework.stereotype.Service;
@Service
public class AuditService {
private final RequestContext context; // a proxy
public AuditService(RequestContext context) {
this.context = context;
}
public void record(String action) {
System.out.println(context.requestId() + " " + action);
}
}AuditService stays a singleton, yet record prints the ID of whichever request is running on the calling thread. If you call record from a thread with no active request, such as a scheduled job or an async task, Spring throws a ScopeNotActiveException. Request scope is bound to the request thread, so it does not follow work you hand to another thread unless you propagate the request attributes yourself.
Choosing a scope
| Situation | Scope |
|---|---|
| Stateless service, repository or configuration | `singleton` |
| Object with mutable per-use state, created on demand | `prototype`, obtained through `ObjectProvider` |
| Data tied to one HTTP request | `request` with a proxy |
| Data tied to one user across requests | `session` with a proxy |
Default to singleton. Reach for another scope only when an object really carries state that must not be shared.
Summary of failure modes
- A singleton holding a prototype keeps one copy. Use
ObjectProvider. - A scoped proxy on a stateful prototype splits calls across instances. Use a provider instead.
- A web scope in a non-web context fails at startup or first lookup.
- A web-scoped bean used off the request thread throws
ScopeNotActiveException. - Prototype beans never receive destruction callbacks.
Exercise
A @Service singleton has a constructor parameter of type ReportBuilder, which is declared @Scope("prototype"). Each call to the service's render method still appends to the same text. Why does this happen, and what is the least invasive change that gives each call a new builder?
Show answer
The singleton's constructor runs once, so the container creates and injects one ReportBuilder and the service keeps it for its whole life. The prototype scope only applies when the container is asked for a bean, and it is asked only once here. Change the constructor parameter to ObjectProvider<ReportBuilder> and call getObject() inside render. Each call then asks the container and receives a new instance.
Exercise
You mark a @Component with @RequestScope and inject it into a singleton service. A scheduled job calls the service and fails with ScopeNotActiveException. What is the cause, and what would you change?
Show answer
Request scope exists only while an HTTP request is being handled on the current thread. The scheduled job runs with no request, so the proxy has no target to resolve. Remove the dependency on the request-scoped bean from the code path the job uses. For example, pass the needed value (such as an ID) as a method argument, or give the job its own non-request-scoped bean.