Sub topic 13
Request, Session and Application Scopes
This chapter assumes you know singleton and prototype scope, can write @Component and @Bean classes, and have run a Spring MVC or Spring Boot web application. Scoped proxies get a full chapter later. Here you only need to know that they exist and why the web scopes use them.
Why web scopes exist
Singleton and prototype scope work in any Spring application. A web application has two more lifetimes that matter: one HTTP request, and one user's conversation with the server. Web scopes tie a bean's lifetime to those units, so you do not have to pass per-request data through every method signature or keep it in hand-managed maps.
The web scopes are only available in a web-aware ApplicationContext, such as the one Spring Boot creates for a servlet application. In a plain AnnotationConfigApplicationContext, asking for a request-scoped bean fails with an error saying that no scope is registered for the scope name request.
The scopes
| Scope name | Annotation | One instance per | Destroyed when |
|---|---|---|---|
| `request` | `@RequestScope` | HTTP request | The request completes |
| `session` | `@SessionScope` | HTTP session | The session is invalidated or times out |
| `application` | `@ApplicationScope` | `ServletContext` | The web application shuts down |
@RequestScope, @SessionScope and @ApplicationScope are composed annotations. Each is @Scope with the matching name and proxyMode = ScopedProxyMode.TARGET_CLASS. You can also write @Scope("request") yourself, but then the proxy is not created unless you ask for it.
Request scope
The container creates a new bean instance for each HTTP request and keeps it in the request attributes. Every bean that touches it during that request sees the same instance. When the request ends, Spring calls the bean's destruction callbacks.
import java.util.UUID;
import org.springframework.stereotype.Component;
import org.springframework.web.context.annotation.RequestScope;
@Component
@RequestScope
class RequestInfo {
private final String id = UUID.randomUUID().toString();
String id() {
return id;
}
}Typical uses are a correlation ID, the authenticated user's resolved details, or a small cache that is valid only for one request.
Session scope
A session-scoped bean lives as long as the user's HttpSession. It is created on first use within that session and stored as a session attribute.
import java.util.ArrayList;
import java.util.List;
import org.springframework.stereotype.Component;
import org.springframework.web.context.annotation.SessionScope;
@Component
@SessionScope
class ShoppingCart {
private final List<String> items = new ArrayList<>();
void add(String item) {
items.add(item);
}
List<String> items() {
return List.copyOf(items);
}
}Session beans have two costs you should plan for:
- Memory is held for every active session until it times out. A large object graph multiplied by many users adds up quickly.
- If the container replicates or persists sessions, session beans may be serialized. Make them
Serializable, or the replication fails at runtime.
Application scope
An application-scoped bean has one instance per ServletContext. That sounds like a singleton, and in a single-context application the two behave almost the same. The difference is where the instance is stored. A singleton belongs to the ApplicationContext. An application-scoped bean is stored as a ServletContext attribute, so it is also visible to code that is not managed by Spring, such as a servlet filter that reads that attribute directly.
If you do not need that visibility, prefer a plain singleton.
Injecting into a singleton
Most beans in an application are singletons, and they are created once at startup. A singleton such as AuditService is wired with its dependencies when the context starts, and there is no request at that moment. If the dependency were a plain request-scoped bean, there would be nothing to inject.
The scoped proxy solves this. The singleton receives a proxy, a generated subclass of the bean's class, that looks like the real bean. On each method call the proxy asks the current request (or session) for the real instance and delegates to it.
import org.springframework.stereotype.Service;
@Service
class AuditService {
private final RequestInfo requestInfo;
AuditService(RequestInfo requestInfo) {
this.requestInfo = requestInfo;
}
String currentRequestId() {
return requestInfo.id();
}
}The requestInfo field holds the same proxy for the whole life of the singleton. Calling requestInfo.id() returns the ID of whichever request the calling thread is serving.
Proxy mode
The proxy mode controls how the proxy is built.
| Mode | How it works | Requirement |
|---|---|---|
| `TARGET_CLASS` | Subclass proxy (CGLIB) | The class must not be `final`, and needs a usable constructor path |
| `INTERFACES` | JDK dynamic proxy | The bean must implement an interface, and injection points must use that interface |
| `NO` | No proxy | You must obtain the bean another way |
The composed annotations use TARGET_CLASS, so you can inject the concrete class. If you write @Scope("request") with no proxy mode, injecting it into a singleton fails at startup with a scope-not-active error.
Alternatives to a proxy
You can leave the bean unproxied and look it up when you need it. ObjectProvider works for this, as it does with prototype beans.
import org.springframework.beans.factory.ObjectProvider;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;
@Component
@Scope("request")
class RequestTimer {
private final long start = System.nanoTime();
long elapsedNanos() {
return System.nanoTime() - start;
}
}
@Service
class TimingService {
private final ObjectProvider<RequestTimer> timer;
TimingService(ObjectProvider<RequestTimer> timer) {
this.timer = timer;
}
long elapsed() {
return timer.getObject().elapsedNanos();
}
}Here nothing is proxied. getObject() runs at call time, inside a request, and returns the current instance. The trade-off is that your code now depends on Spring's lookup type, and you must remember to call getObject() each time rather than caching the result in a field.
Lifecycle details
Request and session beans go through the normal lifecycle: constructor, injection, initialization callbacks. The difference is that creation happens lazily, on the first access within the request or session, not at startup. Destruction callbacks run when the request or session ends, which makes @PreDestroy reliable here, unlike with prototype beans.
Some points to keep in mind:
- The proxy itself is a singleton and is created at startup. The target bean behind it is created on demand.
- Calling a request-scoped bean from a thread that is not serving a request, such as an
@Asyncmethod, a scheduled task or a new thread you start, fails withIllegalStateException: No thread-bound request found. The request attributes are bound to the original thread. - Session beans are shared by concurrent requests from the same user, for example two browser tabs. Their state needs thread safety.
- Request beans are safe from this problem in the common case, because one request is normally handled by one thread.
Choosing a scope
| Need | Scope |
|---|---|
| Data valid for one request only | `request` |
| Data tied to one logged-in user's browser session | `session` |
| One shared instance that must also be visible through the `ServletContext` | `application` |
| One shared instance, nothing web-specific | `singleton` |
| A new instance on every injection or lookup | `prototype` |
Prefer the narrowest scope that works. Wider scopes mean more shared state, more thread-safety concerns and longer memory retention.
Common errors
- No scope registered for scope name 'request'. The context is not web-aware. Run inside a web application, or in tests use a web test setup such as
@SpringBootTestwith a web environment or@WebMvcTest. - Scope 'request' is not active for the current thread. A request-scoped bean without a proxy was injected into a singleton, or accessed outside a request. Add the proxy, use
ObjectProvider, or move the work into the request thread. - Proxy creation fails on a final class.
TARGET_CLASSneeds a subclass. Removefinalor extract an interface and useINTERFACES. - Session replication errors. The session bean, or something it references, is not
Serializable.
Exercise
A singleton ReportService has a constructor parameter of type UserPrefs, and UserPrefs is annotated @Component @Scope("session") with no proxy mode. The application fails at startup. Why, and what are two ways to fix it?
Show answer
At startup the singleton is created with no HTTP session active, so the container has no session to take a UserPrefs from. Fix 1: annotate the bean with @SessionScope, or use @Scope(value = "session", proxyMode = ScopedProxyMode.TARGET_CLASS), so the singleton receives a proxy that resolves the real bean on each call. Fix 2: inject ObjectProvider<UserPrefs> into ReportService and call getObject() inside methods that run during a request.
Exercise
A @RequestScope bean is used from a method annotated @Async, and the call throws IllegalStateException: No thread-bound request found. What is the cause?
Show answer
The request attributes are bound to the thread that handles the HTTP request. The @Async method runs on a different thread from an executor, which has no request bound to it. Copy the needed values into a plain object or method argument before the async call, instead of reading the request-scoped bean on the other thread.