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 Scope interface, whose main method is get(name, objectFactory): return the object stored under this name, or create it with the factory and store it.

Spring's built-in scopes
ScopeOne instance perAvailable inBest for
singleton (default)Application contextAny contextStateless services, repositories, clients, configuration
prototypeRequest to the container (getBean or injection)Any contextStateful helper objects that each caller owns
requestHTTP requestWeb-aware contextData gathered while handling one request
sessionHTTP sessionWeb-aware contextPer-user state, such as a shopping basket
applicationServletContextWeb-aware contextState shared by several contexts in one web application
websocketWebSocket sessionWeb-aware context with WebSocket supportPer-connection state in STOMP messaging
Custom, for example threadWhatever the Scope implementation decidesRegistered by youSpecial 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-web, and the mock request and session classes from spring-test, so that it can run without a server.

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:

Java
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();
    }
}
Output
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 getBean calls returned the same pricing service, id 1. CheckoutService also got id 1, although its @Bean method calls pricingService() as if it were a plain method. In a @Configuration class, Spring intercepts that call and returns the existing singleton.
  • 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"), or with the constants ConfigurableBeanFactory.SCOPE_PROTOTYPE and SCOPE_SINGLETON. It goes on a @Bean method or on a @Component class.

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:

Java
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]);
        }
    }
}
Output
Hello, bob (request was for alice)
Hello, bob (request was for bob)
  • Alice's request stored alice in the field and then waited. Bob's request stored bob in the same field, because there is only one GreetingService.
  • When Alice's request continued, it read the field and greeted Bob: Hello, bob (request was for alice). Under real traffic this shows up as one user occasionally seeing another user's data, which is hard to reproduce.

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 ConcurrentHashMap or AtomicLong. Changing the scope to prototype is not the fix here: the controller that holds the service is itself a singleton, as the next section shows.

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:

Java
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());
        }
    }
}
Output
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.
  • ObjectProvider<Invoice> created invoices 2, 3 and 4. The provider is injected once, but each getObject() call asks the container again. This is Spring's own type, and it also offers getIfAvailable() and stream() for optional or multiple beans.
  • jakarta.inject.Provider<Invoice> did the same for 5, 6 and 7. It is the standard JSR-330 interface, and needs the jakarta.inject-api jar.
  • The @Lookup method created 8, 9 and 10. Spring generated a subclass of WithLookup at startup and overrode newInvoice() to call getBean; the body that returns null never runs. This is method injection, and it needs a class that CGLIB can subclass, so it does not work on @Bean methods that call a constructor themselves or on final classes.
  • The scoped proxy gave 11 then 12 inside a single next() call. The injected Receipt 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.

ObjectProvider is usually the clearest choice: the code says plainly that it asks for a new instance each time. The dependency injection page covers ObjectProvider for optional dependencies too.

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, DispatcherServlet binds the request with RequestContextHolder before calling your controller. This program does the same by hand with mock requests, so that it runs without a server. Alice sends two requests in one session and Bob sends one in another:

Java
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();
    }
}
Output
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 RequestInfo that Spring injected into the singleton controller is WebScopes$RequestInfo$$SpringCGLIB$$0, a scoped proxy. @RequestScope, @SessionScope and @ApplicationScope all default to proxyMode = ScopedProxyMode.TARGET_CLASS, so the proxy is created without any extra setting.
  • Each request got its own request bean, 1, 2 and 3, and each one's @PreDestroy ran when the request completed. Unlike prototypes, request and session beans get their destroy callbacks.
  • 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 ServletContext attribute named scopedTarget.webScopes.SiteStats. That is how it differs from a singleton: it is one per web application, visible to every context and servlet in it.
  • Called outside a request, the proxy failed with ScopeNotActiveException: Scope 'request' is not active for the current thread. You see this when a request-scoped bean is used from a scheduled task, an @Async method, or any thread other than the request's.

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") you have to add proxyMode yourself. The default proxy is a CGLIB subclass, so the scoped class must not be final. ScopedProxyMode.INTERFACES creates a JDK proxy instead, which requires an interface that every injection point uses.

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 request and session scoped beans are a Spring MVC feature.

Custom scopes: the thread scope

Spring ships a SimpleThreadScope that keeps one instance per thread, but does not register it, so you add it with a CustomScopeConfigurer. This program gives each thread its own audit trail behind one shared proxy:

Java
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"));
        }
    }
}
Output
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, view order and, after the worker finished, logout.
  • The worker thread used the same proxy object, trail, but reached trail 2, with only its own two entries.

The Javadoc warns that SimpleThreadScope does not clean up the objects it holds. In a thread pool, threads are reused, so the next task on the same thread would see the previous task's trail. For web requests, use the request scope, which ends with the request. A custom scope of your own implements Scope.get and remove, and registerDestructionCallback if it can tell when objects end; the CustomScopeConfigurer is declared static because it is a bean factory post-processor.

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:

Java
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));
        }
    }
}
Output
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.
  • getBean 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.
  • 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 BeanPostProcessor and the init callbacks.
  • 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 @PreDestroy on prototypes, because it keeps no reference to them. The bean 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 Serializable, and so must everything it holds.
  • Request beans on other threads: code started from a request on another thread, such as @Async or CompletableFuture, cannot see request beans. Copy the values you need into method parameters first.
  • Lazy singletons are still singletons: @Lazy changes when a singleton is created, not how many are created.

Choosing a scope

Which scope fits which bean
BeanScope
Service, repository, client, mapper with no per-call stateSingleton, the default
Cache or counter shared by all callersSingleton with thread-safe fields
Stateful helper that each caller owns, such as a builderPrototype, obtained through ObjectProvider
Data collected while handling one HTTP request@RequestScope, or simply method parameters
Per-user state that spans requests@SessionScope, kept small and serializable
State shared by several Spring contexts in one web application@ApplicationScope
Per-thread state outside web requestsA 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 or rely on the scoped proxy that the web scope annotations create. The inversion of control page explains the container that manages these scopes, and Java configuration covers @Bean methods.