00:00

Spring Bean Scopes

Last updated:

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.

Analogy: In an office, the printer is shared by everyone (singleton). Paper cups are new for every coffee (prototype). A visitor badge lasts for one visit (request). A locker is yours for your whole stay (session). The building's opening hours are the same for all (application).

2. The Spring Bean Scopes at a Glance

ScopeInstancesLives untilAvailable inAnnotation
singletonOne per containerThe context closesEvery applicationDefault, no annotation
prototypeA new one per request to the containerThe caller drops it (no destroy callback)Every application@Scope("prototype")
requestOne per HTTP requestThe request completesWeb applications@RequestScope
sessionOne per HTTP sessionThe session expires or is invalidatedWeb applications@SessionScope
applicationOne per ServletContextThe web application stopsWeb applications@ApplicationScope
websocketOne per WebSocket sessionThe WebSocket session closesSTOMP WebSocket applications@Scope("websocket")
How many instances each scope createsFor three incoming HTTP requests, two of them from the same user session, a singleton bean has one instance shared by all three. A session-scoped bean has two instances, one per user session. A request-scoped bean has three instances, one per request. A prototype bean gets a new instance every time it is looked up or injected, regardless of requests. Request 1 user A Request 2 user A (same session) Request 3 user B Singleton 1 instance shared by all requests Session A cart of user A Session B cart of user B Request bean 1 Request bean 2 Request bean 3 Incoming requests Singleton scope Session scope Request scope
Three requests from two users: one singleton, two session beans, three request beans; prototypes depend on how often they are requested.

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.

PriceQuote.java
@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.

Requirement: request, session and application scopes need a web-aware context. Spring Boot provides one automatically in Spring MVC applications. In a non-web application, using these scopes fails with "No Scope registered for scope name".

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.

How a scoped proxy routes calls to the current request's beanA singleton controller holds a reference to a proxy, not to a real request-scoped bean. When the controller calls a method during request 1, the proxy looks up the instance stored for request 1 and forwards the call. During request 2 the same proxy forwards to the instance for request 2. Singleton CartController Scoped proxy same type, no state of its own calls Instance for request 1 stored in the request Instance for request 2 stored in the request
The singleton always talks to the same proxy; the proxy finds the right instance for the current request or session.

@RequestScope, @SessionScope and @ApplicationScope create a class-based (CGLIB) proxy by default. With plain @Scope, ask for one explicitly:

TenantContext.java
@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

ShoppingCart.java
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

RequestInfo.java
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

CartController.java
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

Terminal
# 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"
Responses
{"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.

Production note: session state lives in one server's memory. With several instances behind a load balancer, use sticky sessions or store sessions centrally with Spring Session (for example in Redis). Session-scoped beans should then be 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:

ScopeConfig.java
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

ScopeShared between threads?What to do
SingletonYes, by every request threadKeep it stateless, or use thread-safe types and immutable fields
PrototypeOnly if you share the instanceUse each instance in one place
RequestNormally one thread per requestUsually safe; take care if you pass it to async tasks
SessionYes, by parallel requests from one userSynchronize or use concurrent collections, as the cart does
ApplicationYesSame 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 @Async method, 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 ObjectProvider or @Lookup.
  • Mutable fields in singletons. A field such as private String currentUser in a service is shared by all users at the same time.
  • Final methods on proxied classes. CGLIB proxies cannot intercept final methods, 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 @RequestScope and @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