Spring Bean Scopes
Spring bean scopes decide how many instances of a bean exist and how long each one lives. By default every bean is a singleton: one shared instance for the whole application. Other scopes give you a new instance every time you ask, one per HTTP request, one per user session, or one per WebSocket session. Choosing the right scope keeps data where it belongs; choosing the wrong one leaks one user's data to another or creates objects you did not expect.
This tutorial covers all six built-in scopes, explains scoped proxies and why web-scoped beans need them, builds a shopping cart with session and request scope, shows how to register a custom scope, and lists the thread-safety rules for each scope.
1. What Is a Bean Scope?
A scope is a rule the container applies when someone asks for a bean: "return the existing instance" or "create a new one". It also decides when the instance is destroyed. You set it with @Scope or with shortcut annotations such as @RequestScope, on a @Component class or a @Bean method.
2. The Spring Bean Scopes at a Glance
| Scope | Instances | Lives until | Available in | Annotation |
|---|---|---|---|---|
singleton | One per container | The context closes | Every application | Default, no annotation |
prototype | A new one per request to the container | The caller drops it (no destroy callback) | Every application | @Scope("prototype") |
request | One per HTTP request | The request completes | Web applications | @RequestScope |
session | One per HTTP session | The session expires or is invalidated | Web applications | @SessionScope |
application | One per ServletContext | The web application stops | Web applications | @ApplicationScope |
websocket | One per WebSocket session | The WebSocket session closes | STOMP WebSocket applications | @Scope("websocket") |
3. Singleton Scope
The singleton scope is the default. The container creates one instance (at startup, unless it is lazy) and returns that same instance to every caller. Services, repositories, controllers and clients should all be singletons.
Spring's singleton is "one per container", not "one per JVM" like the Singleton design pattern. Two application contexts in one JVM each have their own instance, and you can still create more instances with new. Also, two @Bean methods returning the same class create two separate singleton beans.
4. Prototype Scope
A prototype bean is created fresh every time it is requested from the container: each getBean() call, each injection point and each ObjectProvider.getObject() call. Use it for stateful helper objects that must not be shared, such as a builder or a per-task calculator.
@Component
@Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE)
public class PriceQuote {
private final List<String> lines = new ArrayList<>();
// stateful: each user of a quote needs its own instance
}
Two things to remember: injecting a prototype into a singleton's constructor gives that singleton one instance for its whole life, and Spring never calls destroy callbacks on prototypes. For a fresh instance per call, inject ObjectProvider<PriceQuote>; see types of dependency injection.
5. Web Scopes: Request, Session, Application and WebSocket
5.1 Request Scope
One instance per HTTP request, destroyed when the response is complete. Good for data collected during one request, such as the caller's tenant or a correlation ID that several services read.
5.2 Session Scope
One instance per HTTP session, the server-side state tied to a user's session cookie. Good for small per-user state in server-rendered applications, such as a shopping cart or a multi-step form. Stateless REST APIs with token authentication usually have no session.
5.3 Application Scope
One instance per ServletContext. In a Spring Boot application there is one servlet context and one application context, so this behaves almost like a singleton. The difference is that the bean is also stored as a ServletContext attribute, visible to non-Spring code in the same web application.
5.4 WebSocket Scope
One instance per WebSocket session, for applications using STOMP messaging over WebSocket. See WebSockets with Spring Boot.
6. Scoped Proxies: Using Short-Lived Beans in Singletons
A singleton controller is created once at startup, but a request-scoped bean only exists while a request is running. How can the controller hold a reference to it? Through a scoped proxy: Spring injects a stand-in object of the same type. Each method call on the proxy looks up the real instance for the current request or session and forwards the call.
@RequestScope, @SessionScope and @ApplicationScope create a class-based (CGLIB) proxy by default. With plain @Scope, ask for one explicitly:
@Component
@Scope(value = WebApplicationContext.SCOPE_REQUEST, proxyMode = ScopedProxyMode.TARGET_CLASS)
public class TenantContext {
private String tenantId;
// getters and setters
}
Alternatively, skip the proxy and inject ObjectProvider<TenantContext>, calling getObject() inside the request.
7. A Complete Example: A Shopping Cart with Session Scope
A server-side cart lives in the user's session, while a request-scoped bean records which request touched it. A singleton controller uses both through scoped proxies.
7.1 The Session-Scoped Cart
package com.javabytechie.shop.cart;
import java.io.Serializable;
import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.Map;
import org.springframework.stereotype.Component;
import org.springframework.web.context.annotation.SessionScope;
@Component
@SessionScope
public class ShoppingCart implements Serializable {
private final Map<String, Integer> items = new LinkedHashMap<>();
public synchronized void add(String sku, int quantity) {
items.merge(sku, quantity, Integer::sum);
}
public synchronized Map<String, Integer> items() {
return Collections.unmodifiableMap(new LinkedHashMap<>(items));
}
}
7.2 The Request-Scoped Bean
package com.javabytechie.shop.cart;
import java.util.UUID;
import org.springframework.stereotype.Component;
import org.springframework.web.context.annotation.RequestScope;
@Component
@RequestScope
public class RequestInfo {
private final String requestId = UUID.randomUUID().toString().substring(0, 8);
public String requestId() {
return requestId;
}
}
7.3 The Singleton Controller
package com.javabytechie.shop.cart;
import java.util.Map;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping("/api/cart")
public class CartController {
private static final Logger log = LoggerFactory.getLogger(CartController.class);
private final ShoppingCart cart; // proxy to the current session's cart
private final RequestInfo requestInfo; // proxy to the current request's bean
public CartController(ShoppingCart cart, RequestInfo requestInfo) {
this.cart = cart;
this.requestInfo = requestInfo;
}
@PostMapping("/items")
public CartView add(@RequestParam String sku, @RequestParam int quantity) {
cart.add(sku, quantity);
log.info("Request {} added {} x {}", requestInfo.requestId(), quantity, sku);
return view();
}
@GetMapping
public CartView view() {
return new CartView(requestInfo.requestId(), cart.items());
}
public record CartView(String requestId, Map<String, Integer> items) {
}
}
7.4 Try It with Two Users
# user A keeps a cookie jar, so both calls share one session
curl -s -c a.txt -b a.txt -X POST "localhost:8080/api/cart/items?sku=KB-100&quantity=1"
curl -s -c a.txt -b a.txt -X POST "localhost:8080/api/cart/items?sku=MS-200&quantity=2"
# user B has a separate cookie jar
curl -s -c b.txt -b b.txt "localhost:8080/api/cart"
{"requestId":"1c9e04aa","items":{"KB-100":1}}
{"requestId":"7b2f61d0","items":{"KB-100":1,"MS-200":2}}
{"requestId":"e4a8c312","items":{}}
User A's cart grows across requests, user B sees an empty cart, and every request has its own request ID, all through one singleton controller. Your request IDs will differ.
Serializable, as ShoppingCart is.8. Creating a Custom Scope
A scope is an implementation of the Scope interface, registered under a name. Spring ships SimpleThreadScope (one instance per thread) but does not register it by default. Register it with a CustomScopeConfigurer, a bean factory post-processor, declared in a static method:
package com.javabytechie.shop.config;
import org.springframework.beans.factory.config.CustomScopeConfigurer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.support.SimpleThreadScope;
@Configuration
class ScopeConfig {
@Bean
static CustomScopeConfigurer threadScope() {
CustomScopeConfigurer configurer = new CustomScopeConfigurer();
configurer.addScope("thread", new SimpleThreadScope());
return configurer;
}
}
Beans annotated with @Scope("thread") now get one instance per thread. SimpleThreadScope never calls destroy callbacks, and with thread pools or virtual threads the "per thread" lifetime is rarely what you want, so prefer passing data explicitly or using request scope. The static keyword is explained in BeanFactoryPostProcessor.
9. Scopes and Thread Safety
| Scope | Shared between threads? | What to do |
|---|---|---|
| Singleton | Yes, by every request thread | Keep it stateless, or use thread-safe types and immutable fields |
| Prototype | Only if you share the instance | Use each instance in one place |
| Request | Normally one thread per request | Usually safe; take care if you pass it to async tasks |
| Session | Yes, by parallel requests from one user | Synchronize or use concurrent collections, as the cart does |
| Application | Yes | Same rules as singleton |
10. Common Pitfalls
- "Scope 'request' is not active for the current thread". A request-scoped bean was used outside a request, for example in an
@Asyncmethod, a scheduled task or at startup. Pass the needed values as method arguments instead. - Prototype injected once. A prototype in a singleton's constructor is created once. Use
ObjectProvideror@Lookup. - Mutable fields in singletons. A field such as
private String currentUserin a service is shared by all users at the same time. - Final methods on proxied classes. CGLIB proxies cannot intercept
finalmethods, so calls to them reach the proxy's own empty state. - Large session beans. Every active user holds a copy in memory; keep session state small.
11. Best Practices
- Default to stateless singletons for services, repositories and controllers.
- Use prototype only for stateful helpers, obtained through
ObjectProvider. - Use the shortcut annotations
@RequestScopeand@SessionScope, which add the proxy for you. - Keep session-scoped beans small and serializable, and plan for multiple instances.
- Never read web-scoped beans from background threads; copy the values you need first.
- Prefer explicit parameters over custom scopes unless a framework requires one.
12. Summary
Spring bean scopes control how many instances of a bean exist and how long they live. Singleton, the default, shares one instance per container; prototype creates a new one per lookup and is never destroyed by Spring; request, session, application and websocket tie instances to web lifetimes. Short-lived beans are used from singletons through scoped proxies, which @RequestScope and @SessionScope create automatically, and custom scopes can be registered with CustomScopeConfigurer. Keep singletons stateless, use narrower scopes only for real per-request or per-user state, and remember that each scope has its own thread-safety rules.
13. References
Spring Bean Scopes Interview Questions and Answers
Common interview questions on Spring Bean Scopes, from basic to scenario-based, with short answers you can explain in your own words.
Q. How is Spring's singleton scope different from the Singleton design pattern?
Answer: The design pattern guarantees one instance per class loader, usually with a private constructor and a static accessor. Spring's singleton means one instance per bean definition per container: two contexts have two instances, two @Bean methods for the same class create two beans, and anyone can still call new. The class itself stays an ordinary, testable class.
Q. Why do you need a scoped proxy to inject a request-scoped bean into a singleton?
Answer: The singleton is created once at startup, when no request exists, and keeps its references forever. A scoped proxy is injected instead of a real instance; on every method call it looks up the instance belonging to the current request and delegates to it. Without the proxy, startup would fail because there is no active request scope. @RequestScope and @SessionScope create the proxy by default.
Q. What happens if an @Async method uses a request-scoped bean?
Answer: It typically fails with "Scope 'request' is not active for the current thread", because request attributes are bound to the thread handling the request and the async method runs on another thread. Even if it worked, the request might finish before the task. Copy the needed values, such as a tenant ID, into method arguments before starting the async work.
Q. What is the difference between application scope and singleton scope?
Answer: A singleton is one instance per Spring container. An application-scoped bean is one instance per ServletContext and is also exposed as a servlet context attribute. If several Spring contexts share one servlet context, they share the application-scoped bean but each has its own singleton. In a typical Spring Boot application with one context, the two behave almost the same.
Q. How do you register a custom scope such as a thread scope?
Answer: Implement the Scope interface or use an existing one such as SimpleThreadScope, and register it under a name with a CustomScopeConfigurer declared in a static @Bean method (or by calling registerScope on the bean factory). Beans then use @Scope("thread"). Custom scopes must decide when to destroy instances; SimpleThreadScope never does.
Q. A session-scoped cart works on one server but loses items after scaling to three instances. Why, and what are the options?
Answer: Sessions are stored in each server's memory, so a request routed to another instance finds a different, empty session. Options: sticky sessions at the load balancer (simple, but sessions are lost when an instance stops), a shared session store with Spring Session backed by Redis or a database (session beans must then be serializable), or moving the cart out of the session into a database or cache keyed by user ID, which also suits stateless APIs.