Spring bean scopes: how many instances, and for how long
A bean's scope decides how many instances Spring creates and how long each one lives: one for the whole context, one per request for it, one per HTTP request or session. This page runs every built-in scope, shows the classic trap of a prototype injected into a singleton and four ways to fix it, and explains the scoped proxies that make request and session beans work.
Contents
What a bean scope is
A bean definition is a recipe: it says which class to create and which dependencies to give it. The scope says how often the container follows that recipe, and where it keeps the result. For a singleton, the container creates one object and stores it in a map inside the bean factory, so every later request for the bean returns that object. For a prototype, the container creates a new object on every request and keeps nothing.
The other scopes store the object somewhere with a shorter life. A request-scoped bean is stored as an attribute of the current HTTP request, and a session-scoped bean as an attribute of the HTTP session. When the request or session ends, the object goes with it. Each of these scopes is an implementation of Spring's Scopeget(name, objectFactory)
| Scope | One instance per | Available in | Best for |
|---|---|---|---|
singleton | Application context | Any context | Stateless services, repositories, clients, configuration |
prototype | Request to the container (getBean | Any context | Stateful helper objects that each caller owns |
request | HTTP request | Web-aware context | Data gathered while handling one request |
session | HTTP session | Web-aware context | Per-user state, such as a shopping basket |
application | ServletContext | Web-aware context | State shared by several contexts in one web application |
websocket | WebSocket session | Web-aware context with WebSocket support | Per-connection state in STOMP messaging |
Custom, for example thread | Whatever the Scope | Registered by you | Special cases, such as per-thread state in batch jobs |
Two ideas come up again and again on this page. A dependency is injected once, when the bean that needs it is created. And a bean with a short scope can still be injected into a long-lived one, through a scoped proxy: a stand-in object that looks up the real instance in its scope on every method call.
The examples are complete programs on Spring Framework 7.0 without Spring Boot. The web scope example adds spring-webspring-test
Singleton and prototype
This program declares one bean of each scope, counts how many objects each constructor creates, and then starts a second context from the same configuration to show what "one per context" means:
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Scope;
public class SingletonVsPrototype {
static int pricingCreated = 0;
static int cartsCreated = 0;
static class PricingService {
final int id = ++pricingCreated;
}
static class ShoppingCart {
final int id = ++cartsCreated;
}
static class CheckoutService {
final PricingService pricing;
CheckoutService(PricingService pricing) {
this.pricing = pricing;
}
}
@Configuration
static class Config {
@Bean // singleton is the default scope
PricingService pricingService() {
return new PricingService();
}
@Bean
@Scope("prototype")
ShoppingCart shoppingCart() {
return new ShoppingCart();
}
@Bean
CheckoutService checkoutService() {
return new CheckoutService(pricingService()); // a call, not a new object
}
}
public static void main(String[] args) {
var context = new AnnotationConfigApplicationContext(Config.class);
System.out.println("After startup: pricing services = " + pricingCreated
+ ", carts = " + cartsCreated);
PricingService p1 = context.getBean(PricingService.class);
PricingService p2 = context.getBean(PricingService.class);
System.out.println("singleton : same object = " + (p1 == p2) + ", id " + p1.id);
System.out.println(" checkout uses id "
+ context.getBean(CheckoutService.class).pricing.id);
ShoppingCart c1 = context.getBean(ShoppingCart.class);
ShoppingCart c2 = context.getBean(ShoppingCart.class);
System.out.println("prototype : same object = " + (c1 == c2)
+ ", ids " + c1.id + " and " + c2.id);
var second = new AnnotationConfigApplicationContext(Config.class);
System.out.println("second context: pricing id "
+ second.getBean(PricingService.class).id
+ ", same as first = " + (second.getBean(PricingService.class) == p1));
second.close();
context.close();
}
}
After startup: pricing services = 1, carts = 0
singleton : same object = true, id 1
checkout uses id 1
prototype : same object = false, ids 1 and 2
second context: pricing id 2, same as first = false
- After startup, one pricing service existed and zero carts. Singletons are created eagerly during startup; prototypes only when someone asks for one.
- Two
calls returned the same pricing service, id 1.getBean also got id 1, although itsCheckoutService method calls@Bean as if it were a plain method. In apricingService() class, Spring intercepts that call and returns the existing singleton.@Configuration - Two requests for a cart returned two different objects, ids 1 and 2.
- The second context created its own pricing service, id 2. A Spring singleton is one instance per bean definition per container, not one per JVM like the classic Singleton pattern. Tests that start several contexts, and applications with parent and child contexts, have several "singletons" of the same class.
Declare a scope with @Scope("prototype")ConfigurableBeanFactory.SCOPE_PROTOTYPESCOPE_SINGLETON@Bean@Component
Singletons are shared between threads
A singleton is shared by every thread that uses it. In a web application each request runs on its own thread, so a field in a singleton that holds data for one request will be overwritten by the next. This greeting service keeps the current user in a field. Two latches make the two requests interleave the same way on every run, the way they would under real load:
import java.util.concurrent.CountDownLatch;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.stereotype.Service;
public class SharedStateTrap {
@Service
static class GreetingService {
private String currentUser; // state of one request, stored in a shared bean
String greet(String user, CountDownLatch saved, CountDownLatch otherSaved)
throws InterruptedException {
currentUser = user;
saved.countDown();
otherSaved.await(); // the other request runs here
return "Hello, " + currentUser + " (request was for " + user + ")";
}
}
public static void main(String[] args) throws Exception {
try (var context = new AnnotationConfigApplicationContext(GreetingService.class)) {
GreetingService service = context.getBean(GreetingService.class);
CountDownLatch aliceSaved = new CountDownLatch(1);
CountDownLatch bobSaved = new CountDownLatch(1);
String[] replies = new String[2];
Thread alice = new Thread(() -> {
try {
replies[0] = service.greet("alice", aliceSaved, bobSaved);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
});
Thread bob = new Thread(() -> {
try {
aliceSaved.await(); // bob arrives after alice stored her name
replies[1] = service.greet("bob", bobSaved, new CountDownLatch(0));
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
});
alice.start();
bob.start();
alice.join();
bob.join();
System.out.println(replies[0]);
System.out.println(replies[1]);
}
}
}
Hello, bob (request was for alice)
Hello, bob (request was for bob)
- Alice's request stored
in the field and then waited. Bob's request storedalice in the same field, because there is only onebob .GreetingService - When Alice's request continued, it read the field and greeted Bob:
. Under real traffic this shows up as one user occasionally seeing another user's data, which is hard to reproduce.Hello, bob (request was for alice)
Keep singletons stateless: pass per-request data as method parameters or local variables. Shared state that must live in a singleton, such as a cache or a counter, needs a thread-safe type like ConcurrentHashMapAtomicLong
A prototype inside a singleton, and four fixes
A prototype injected into a singleton is created once, when the singleton is created, and then reused for the singleton's whole life. The scope says "new object per request to the container", and injection is one request. This program injects an invoice prototype in five different ways, and asks each holder for three invoices:
import jakarta.inject.Provider;
import org.springframework.beans.factory.ObjectProvider;
import org.springframework.beans.factory.annotation.Lookup;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.Scope;
import org.springframework.context.annotation.ScopedProxyMode;
import org.springframework.stereotype.Component;
public class PrototypeInSingleton {
static int created = 0;
@Component
@Scope("prototype")
public static class Invoice {
private final int number = ++created;
public int number() {
return number;
}
}
@Component
@Scope(value = "prototype", proxyMode = ScopedProxyMode.TARGET_CLASS)
public static class Receipt {
private final int number = ++created;
public int number() {
return number;
}
}
@Component
static class InjectedOnce {
private final Invoice invoice;
InjectedOnce(Invoice invoice) {
this.invoice = invoice;
}
int next() {
return invoice.number();
}
}
@Component
static class WithObjectProvider {
private final ObjectProvider<Invoice> invoices;
WithObjectProvider(ObjectProvider<Invoice> invoices) {
this.invoices = invoices;
}
int next() {
return invoices.getObject().number();
}
}
@Component
static class WithJakartaProvider {
private final Provider<Invoice> invoices;
WithJakartaProvider(Provider<Invoice> invoices) {
this.invoices = invoices;
}
int next() {
return invoices.get().number();
}
}
@Component
static class WithLookup {
@Lookup
Invoice newInvoice() {
return null; // Spring overrides this method in a generated subclass
}
int next() {
return newInvoice().number();
}
}
@Component
static class WithScopedProxy {
private final Receipt receipt;
WithScopedProxy(Receipt receipt) {
this.receipt = receipt;
}
String next() {
return receipt.number() + " then " + receipt.number();
}
}
public static void main(String[] args) {
try (var context = new AnnotationConfigApplicationContext(Invoice.class, Receipt.class,
InjectedOnce.class, WithObjectProvider.class, WithJakartaProvider.class,
WithLookup.class, WithScopedProxy.class)) {
InjectedOnce once = context.getBean(InjectedOnce.class);
System.out.println("constructor injection: " + once.next() + ", " + once.next()
+ ", " + once.next());
WithObjectProvider op = context.getBean(WithObjectProvider.class);
System.out.println("ObjectProvider : " + op.next() + ", " + op.next()
+ ", " + op.next());
WithJakartaProvider jp = context.getBean(WithJakartaProvider.class);
System.out.println("jakarta Provider : " + jp.next() + ", " + jp.next()
+ ", " + jp.next());
WithLookup lookup = context.getBean(WithLookup.class);
System.out.println("@Lookup method : " + lookup.next() + ", " + lookup.next()
+ ", " + lookup.next());
WithScopedProxy proxy = context.getBean(WithScopedProxy.class);
System.out.println("scoped proxy : " + proxy.next());
}
}
}
constructor injection: 1, 1, 1
ObjectProvider : 2, 3, 4
jakarta Provider : 5, 6, 7
@Lookup method : 8, 9, 10
scoped proxy : 11 then 12
- Constructor injection returned invoice 1 three times. The singleton received one invoice at startup and keeps it.
created invoices 2, 3 and 4. The provider is injected once, but eachObjectProvider<Invoice> call asks the container again. This is Spring's own type, and it also offersgetObject() andgetIfAvailable() for optional or multiple beans.stream() did the same for 5, 6 and 7. It is the standard JSR-330 interface, and needs thejakarta.inject.Provider<Invoice> jar.jakarta.inject-api- The
method created 8, 9 and 10. Spring generated a subclass of@Lookup at startup and overrodeWithLookup to callnewInvoice() ; the body that returnsgetBean never runs. This is method injection, and it needs a class that CGLIB can subclass, so it does not work onnull methods that call a constructor themselves or on final classes.@Bean - The scoped proxy gave
inside a single11 then 12 call. The injectednext() is a proxy that creates a new target on every method call, so two calls on the "same" receipt reached two different objects. For a prototype, this is rarely what you want; the proxy fits request and session scopes much better.Receipt
ObjectProviderObjectProvider
Request, session and application scopes
The web scopes need a web-aware context, which registers them at startup, and a current request bound to the thread. In a Spring MVC application, DispatcherServletRequestContextHolder
import jakarta.annotation.PreDestroy;
import org.springframework.beans.factory.BeanCreationException;
import org.springframework.mock.web.MockHttpServletRequest;
import org.springframework.mock.web.MockHttpSession;
import org.springframework.mock.web.MockServletContext;
import org.springframework.stereotype.Component;
import org.springframework.web.context.annotation.ApplicationScope;
import org.springframework.web.context.annotation.RequestScope;
import org.springframework.web.context.annotation.SessionScope;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.context.support.AnnotationConfigWebApplicationContext;
public class WebScopes {
static int requestBeans = 0;
static int sessionBeans = 0;
@Component
@RequestScope
public static class RequestInfo {
private final int id = ++requestBeans;
public int id() {
return id;
}
@PreDestroy
void done() {
System.out.println(" @PreDestroy for request bean " + id);
}
}
@Component
@SessionScope
public static class Basket {
private final int id = ++sessionBeans;
private int items;
public String add() {
items++;
return "basket " + id + " has " + items + " item(s)";
}
}
@Component
@ApplicationScope
public static class SiteStats {
private int visits;
public int visit() {
return ++visits;
}
}
@Component
static class ShopController { // a singleton that holds request and session beans
private final RequestInfo request;
private final Basket basket;
ShopController(RequestInfo request, Basket basket) {
this.request = request;
this.basket = basket;
}
String handle() {
return "request bean " + request.id() + ", " + basket.add();
}
}
static void call(ShopController controller, MockServletContext servletContext,
MockHttpSession session, String label) {
MockHttpServletRequest http = new MockHttpServletRequest(servletContext);
http.setSession(session);
ServletRequestAttributes attributes = new ServletRequestAttributes(http);
RequestContextHolder.setRequestAttributes(attributes); // what DispatcherServlet does
try {
System.out.println(" " + label + ": " + controller.handle());
} finally {
RequestContextHolder.resetRequestAttributes();
attributes.requestCompleted(); // runs destruction callbacks for request beans
}
}
public static void main(String[] args) {
MockServletContext servletContext = new MockServletContext();
var context = new AnnotationConfigWebApplicationContext();
context.setServletContext(servletContext);
context.register(RequestInfo.class, Basket.class, SiteStats.class, ShopController.class);
context.refresh();
ShopController controller = context.getBean(ShopController.class);
System.out.println("Injected request bean class: "
+ context.getBean(RequestInfo.class).getClass().getSimpleName());
MockHttpSession alice = new MockHttpSession(servletContext);
MockHttpSession bob = new MockHttpSession(servletContext);
call(controller, servletContext, alice, "alice, request 1");
call(controller, servletContext, alice, "alice, request 2");
call(controller, servletContext, bob, "bob, request 1");
context.getBean(SiteStats.class).visit();
System.out.println("ServletContext attributes holding SiteStats: "
+ java.util.Collections.list(servletContext.getAttributeNames()).stream()
.filter(name -> name.contains("SiteStats")).toList());
System.out.println("Calling outside a request:");
try {
controller.handle();
} catch (BeanCreationException e) {
String message = e.getMessage();
System.out.println(" " + e.getClass().getSimpleName() + ":");
System.out.println(" " + message.substring(message.indexOf("Scope '"),
message.indexOf(';')));
}
context.close();
}
}
Injected request bean class: WebScopes$RequestInfo$$SpringCGLIB$$0
alice, request 1: request bean 1, basket 1 has 1 item(s)
@PreDestroy for request bean 1
alice, request 2: request bean 2, basket 1 has 2 item(s)
@PreDestroy for request bean 2
bob, request 1: request bean 3, basket 2 has 1 item(s)
@PreDestroy for request bean 3
ServletContext attributes holding SiteStats: [scopedTarget.webScopes.SiteStats]
Calling outside a request:
ScopeNotActiveException:
Scope 'request' is not active for the current thread
- The
that Spring injected into the singleton controller isRequestInfo , a scoped proxy.WebScopes$RequestInfo$$SpringCGLIB$$0 ,@RequestScope and@SessionScope all default to@ApplicationScope , so the proxy is created without any extra setting.proxyMode = ScopedProxyMode.TARGET_CLASS - Each request got its own request bean, 1, 2 and 3, and each one's
ran when the request completed. Unlike prototypes, request and session beans get their destroy callbacks.@PreDestroy - Alice's two requests found the same basket, which went from 1 item to 2 items. Bob's session got basket 2. Each proxy call looked up the object in the current request or session.
- The application-scoped bean is stored as a
attribute namedServletContext . That is how it differs from a singleton: it is one per web application, visible to every context and servlet in it.scopedTarget.webScopes.SiteStats - Called outside a request, the proxy failed with
:ScopeNotActiveException . You see this when a request-scoped bean is used from a scheduled task, anScope 'request' is not active for the current thread method, or any thread other than the request's.@Async
Without the proxy, the singleton controller could not be created at all, because at startup there is no request to take a request bean from. The scope annotations add the proxy for you; with plain @Scope("request")proxyModefinalScopedProxyMode.INTERFACES
In Spring Boot, a web application gets a web-aware context automatically. The same scope names exist in WebFlux, but WebFlux has no request bound to a thread, so requestsession
Custom scopes: the thread scope
Spring ships a SimpleThreadScopeCustomScopeConfigurer
import org.springframework.beans.factory.config.CustomScopeConfigurer;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Scope;
import org.springframework.context.annotation.ScopedProxyMode;
import org.springframework.context.support.SimpleThreadScope;
public class ThreadScopeDemo {
static int created = 0;
public static class AuditTrail {
private final int id;
private final StringBuilder entries = new StringBuilder();
AuditTrail(int id) {
this.id = id;
}
public String add(String entry) {
entries.append(entries.isEmpty() ? "" : ", ").append(entry);
return "trail " + id + " [" + entries + "]";
}
}
@Configuration
static class Config {
@Bean
static CustomScopeConfigurer threadScope() {
CustomScopeConfigurer configurer = new CustomScopeConfigurer();
configurer.addScope("thread", new SimpleThreadScope());
return configurer;
}
@Bean
@Scope(value = "thread", proxyMode = ScopedProxyMode.TARGET_CLASS)
AuditTrail auditTrail() {
synchronized (ThreadScopeDemo.class) {
return new AuditTrail(++created);
}
}
}
public static void main(String[] args) throws InterruptedException {
try (var context = new AnnotationConfigApplicationContext(Config.class)) {
AuditTrail trail = context.getBean(AuditTrail.class); // one proxy for everyone
System.out.println("main : " + trail.add("login"));
System.out.println("main : " + trail.add("view order"));
Thread worker = new Thread(() -> {
System.out.println("worker-1: " + trail.add("import file"));
System.out.println("worker-1: " + trail.add("send report"));
});
worker.start();
worker.join();
System.out.println("main : " + trail.add("logout"));
}
}
}
main : trail 1 [login]
main : trail 1 [login, view order]
worker-1: trail 2 [import file]
worker-1: trail 2 [import file, send report]
main : trail 1 [login, view order, logout]
- The main thread's calls all reached trail 1, which collected
,login and, after the worker finished,view order .logout - The worker thread used the same proxy object,
, but reached trail 2, with only its own two entries.trail
The Javadoc warns that SimpleThreadScopeScope.getremoveregisterDestructionCallbackCustomScopeConfigurerstatic
What each scope costs
Scopes other than singleton do work on every lookup. This rough comparison measures the time per call for four ways of reaching a bean, as the best of 3 runs of 1,000,000 calls each, on a 2-core Intel Xeon at 2.1 GHz with Java 21:
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Scope;
import org.springframework.context.annotation.ScopedProxyMode;
public class ScopeCost {
public static class Counter {
private long value;
public long increment() {
return ++value;
}
}
public static class ProxiedCounter extends Counter {
}
@Configuration
static class Config {
@Bean
Counter singletonCounter() {
return new Counter();
}
@Bean
@Scope("prototype")
Counter prototypeCounter() {
return new Counter();
}
@Bean
@Scope(value = "prototype", proxyMode = ScopedProxyMode.TARGET_CLASS)
ProxiedCounter proxiedCounter() {
return new ProxiedCounter();
}
}
interface Task {
long run(int n);
}
static double nanosPerCall(Task task, int n) {
long best = Long.MAX_VALUE;
long sink = 0;
for (int round = 0; round < 3; round++) {
long start = System.nanoTime();
sink += task.run(n);
best = Math.min(best, System.nanoTime() - start);
}
if (sink == 42) {
System.out.println(); // keeps the JIT from removing the work
}
return (double) best / n;
}
public static void main(String[] args) {
try (var context = new AnnotationConfigApplicationContext(Config.class)) {
Counter singleton = context.getBean("singletonCounter", Counter.class);
ProxiedCounter proxy = context.getBean(ProxiedCounter.class);
int n = 1000000;
System.out.printf("method call on an injected singleton : %7.1f ns%n",
nanosPerCall(count -> {
long sum = 0;
for (int i = 0; i < count; i++) {
sum += singleton.increment();
}
return sum;
}, n));
System.out.printf("getBean(singleton) on every call : %7.1f ns%n",
nanosPerCall(count -> {
long sum = 0;
for (int i = 0; i < count; i++) {
sum += context.getBean("singletonCounter", Counter.class)
.increment();
}
return sum;
}, n));
System.out.printf("getBean(prototype) on every call : %7.1f ns%n",
nanosPerCall(count -> {
long sum = 0;
for (int i = 0; i < count; i++) {
sum += context.getBean("prototypeCounter", Counter.class)
.increment();
}
return sum;
}, n));
System.out.printf("call through a prototype scoped proxy: %7.1f ns%n",
nanosPerCall(count -> {
long sum = 0;
for (int i = 0; i < count; i++) {
sum += proxy.increment();
}
return sum;
}, n));
}
}
}
method call on an injected singleton : 0.4 ns
getBean(singleton) on every call : 16.6 ns
getBean(prototype) on every call : 1632.8 ns
call through a prototype scoped proxy: 1913.9 ns
- A method call on an injected singleton costs a few nanoseconds at most. It is an ordinary Java call, which the JIT compiler can inline.
for a singleton is several times slower, because it looks the name up in a map and checks the type. Still cheap, but there is no reason to do it in a loop.getBean- Creating a prototype takes one to two microseconds, one to two orders of magnitude more than looking up a singleton. Each creation runs the constructor through reflection, then every
and the init callbacks.BeanPostProcessor - A call through a prototype scoped proxy costs about as much as creating a prototype, because the proxy's interceptor asks the container for a new target on every method call.
The exact numbers move by a factor of two or more between runs on this shared machine; the ratios are what to take away. These costs only matter in hot paths. A request-scoped bean is created once per request, which is nothing next to the request itself, but a prototype created inside a loop over a million rows adds a measurable delay.
Pitfalls with scopes
- Prototype destroy callbacks: Spring never calls
on prototypes, because it keeps no reference to them. The@PreDestroybean lifecycle page shows this running. - Scoped proxies and private methods: a CGLIB proxy cannot intercept private methods, so a private method called on the proxy runs on the proxy object itself, not on the real bean in the scope.
- Session beans and clustering: a session-scoped bean is stored in the HTTP session. If sessions are replicated or stored in Redis with Spring Session, the bean must be
, and so must everything it holds.Serializable - Request beans on other threads: code started from a request on another thread, such as
or@Async , cannot see request beans. Copy the values you need into method parameters first.CompletableFuture - Lazy singletons are still singletons:
changes when a singleton is created, not how many are created.@Lazy
Choosing a scope
| Bean | Scope |
|---|---|
| Service, repository, client, mapper with no per-call state | Singleton, the default |
| Cache or counter shared by all callers | Singleton with thread-safe fields |
| Stateful helper that each caller owns, such as a builder | Prototype, obtained through ObjectProvider |
| Data collected while handling one HTTP request | @RequestScope |
| Per-user state that spans requests | @SessionScope |
| State shared by several Spring contexts in one web application | @ApplicationScope |
| Per-thread state outside web requests | A registered thread scope, cleaned up by you |
Most applications need only singletons: keep them stateless and almost every scope question goes away. When you do need a shorter-lived bean inside a singleton, inject an ObjectProvider@Bean