skip to content

What are Spring's web scopes (request, session, application, websocket), and how do they differ from singleton and prototype?

level: juniorimportance: must knowfreq 70%

answer

  1. request/session/application/websocket
  2. @RequestScope / @SessionScope / @ApplicationScope
  3. needs web context + thread-bound request
  4. application ≈ singleton but per ServletContext
  5. No thread-bound request found

basics

~20 s

Web scopes tie a bean's lifetime to a web context: request (one HTTP request), session (one user session), application (the ServletContext), and websocket (a WebSocket session). Singleton lives for the whole container; prototype creates a new instance per lookup.

solid answer

~40 s

Beyond singleton (one shared instance per container) and prototype (a fresh instance every time it's requested), a web-aware ApplicationContext adds four scopes. request: one instance per HTTP request, discarded when the request ends. session: one instance per HTTP session, shared across that user's requests. application: one instance per ServletContext — like a singleton but shared across multiple DispatcherServlets and exposed as a ServletContext attribute. websocket: one instance per WebSocket session. You declare them with @Scope("request") etc., or the meta-annotations @RequestScope, @SessionScope, @ApplicationScope. They require a web environment; RequestContextListener/RequestContextFilter or DispatcherServlet must bind the current request to the thread so Spring can resolve them.

code

java · 14 lines
java
@Component
@RequestScope // = @Scope(value = "request", proxyMode = TARGET_CLASS)
public class RequestContextData {
    private String requestId = UUID.randomUUID().toString();
    public String getRequestId() { return requestId; }
}

@Component
@SessionScope
public class ShoppingCart {
    private final List<String> items = new ArrayList<>();
    public void add(String sku) { items.add(sku); }
    public List<String> items() { return List.copyOf(items); }
}

go deeper

for a junior

Name the four web scopes and contrast with singleton/prototype.

for a middle

Explain the thread-bound-request requirement and RequestContextListener/Filter.

for a senior

Discuss serialization for clustered sessions and application-vs-singleton nuance.

for a principal

Reason about scope choice for state management, clustering/session replication, and avoiding shared mutable state.

## Scopes in Spring A bean's **scope** defines how many instances the container creates and how long each lives. **Standard scopes (any ApplicationContext):** - **singleton** (default): exactly one shared instance per Spring container, created eagerly at startup, cached for the container's whole life. - **prototype**: a brand-new instance every time the bean is injected or fetched via `getBean`. Spring does not manage its full lifecycle — no destruction callback is called. **Web scopes (only in a web-aware context** such as `AnnotationConfigWebApplicationContext` or a Spring Boot web app): - **request** (`@RequestScope` or `@Scope("request")`): one instance per HTTP request. Created on first access during the request, destroyed when the request completes. Good for per-request state (e.g., a request-id holder). - **session** (`@SessionScope` or `@Scope("session")`): one instance per HTTP `HttpSession`. Shared across all requests of that user's session; destroyed when the session is invalidated or times out. Good for per-user shopping-cart-style state. - **application** (`@ApplicationScope` or `@Scope("application")`): one instance per `ServletContext`. Similar to singleton but with two differences: it is scoped to the ServletContext (shared even if the app has multiple DispatcherServlets, each with its own child ApplicationContext) and it is exposed as a `ServletContext` attribute. - **websocket** (`@Scope("websocket")`): one instance per WebSocket session, used with Spring's WebSocket/STOMP support. ## What web scopes require Resolving a request/session-scoped bean needs the current request bound to the executing thread. In a standard Spring MVC app, `DispatcherServlet` binds it automatically via `RequestContextHolder`. Outside DispatcherServlet (e.g., filters, async threads, plain servlets) you register a `RequestContextListener` (a `ServletRequestListener`) or `RequestContextFilter` so the binding exists. If nothing bound the request, Spring throws `BeanCreationException` wrapping an `IllegalStateException: No thread-bound request found`. ## Declaring them ```java @Component @RequestScope public class RequestData { /* per-request state */ } ``` The meta-annotations `@RequestScope`, `@SessionScope`, `@ApplicationScope` are shorthands that also set `proxyMode = TARGET_CLASS` by default, which matters when injecting a short-lived bean into a singleton (covered separately). ## Gotchas - Web scopes are useless (and unresolvable) in a non-web context — e.g., a batch job or a plain `ApplicationContext`. - Session-scoped beans must be `Serializable` if the session can be passivated/replicated across a cluster. - Don't confuse **application** scope with **singleton**: application is per-ServletContext and published as a ServletContext attribute; singleton is per Spring container.

  • What happens if you try to use a request-scoped bean in a background thread with no HTTP request?
    Resolution fails with IllegalStateException: 'No thread-bound request found' because RequestContextHolder has nothing bound to that thread. You'd need to propagate the request context or avoid request scope there.
  • How is application scope different from a singleton?
    Both give roughly one instance, but application scope is bound to the ServletContext (shared across multiple DispatcherServlet child contexts) and is also registered as a ServletContext attribute; singleton is one-per-Spring-container.

saying these in an interview costs you the question

  • Claiming web scopes work in any ApplicationContext including non-web apps
  • Saying application scope and singleton are identical
  • Thinking prototype and request scope are the same thing

context