Sub topic 13
Request, session and application scopes
This chapter assumes you know singleton and prototype scope, and that you can run a Spring Boot web application. The three web scopes tie a bean's lifetime to something in a web application: one HTTP request, one user session, or the whole servlet context.
The three scopes
| Scope | One instance per | Annotation | Destroyed when |
|---|---|---|---|
| request | HTTP request | `@RequestScope` | The request finishes |
| session | HTTP session | `@SessionScope` | The session expires or is invalidated |
| application | `ServletContext` | `@ApplicationScope` | The web application shuts down |
These scopes exist only in a web-aware ApplicationContext. Spring Boot creates one for web applications. In a plain AnnotationConfigApplicationContext, resolving such a bean fails with IllegalStateException: No Scope registered for scope name 'request'.
Application scope looks like singleton scope, but it is not the same. A singleton lives once per ApplicationContext. An application-scoped bean is stored as an attribute of the ServletContext. If several contexts share one ServletContext, they share the application-scoped bean too. In a typical Spring Boot application the two behave the same.
A request-scoped bean
@RequestScope is shorthand for @Scope(value = "request", proxyMode = ScopedProxyMode.TARGET_CLASS). The @SessionScope and @ApplicationScope annotations work the same way. The proxy is what lets a singleton hold the bean.
import java.util.UUID;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;
import org.springframework.web.context.annotation.RequestScope;
@Component
@RequestScope
class RequestInfo {
private final String id = UUID.randomUUID().toString();
String id() {
return id;
}
}
@Service
class AuditService {
private final RequestInfo requestInfo;
AuditService(RequestInfo requestInfo) {
this.requestInfo = requestInfo;
}
String currentRequestId() {
return requestInfo.id();
}
}AuditService is a singleton, so Spring creates it once at startup, when no request exists. What it receives is a proxy, a generated subclass of RequestInfo. Each call on the proxy looks up the RequestInfo that belongs to the current request and forwards the call to it. Two concurrent requests therefore see different ids through the same AuditService.
Common errors
- No thread-bound request. Calling the proxy outside a request thread throws
IllegalStateException: No thread-bound request found. This happens in@Asyncmethods,@Scheduledtasks and threads you start yourself. Read the value in the request thread and pass it as an argument. - Final classes.
TARGET_CLASSproxies subclass your bean, so afinalclass orfinalmethod cannot be proxied correctly. UseproxyMode = ScopedProxyMode.INTERFACESif the bean implements an interface. - Session state that is not serializable. Servlet containers may persist sessions. Make session-scoped beans
Serializableif you rely on that. - Shared mutable state. An application-scoped bean is reachable from every thread, so it needs the same thread-safety care as a singleton.
Exercise
A singleton ReportService injects a request-scoped RequestInfo and calls it from a method annotated with @Scheduled. What happens, and why?
Show answer
The call throws IllegalStateException: No thread-bound request found. The scheduled task runs on a scheduler thread, outside any HTTP request. The scoped proxy cannot find a current request, so it has no RequestInfo to forward the call to.