wasAsked.

Explain singleton, prototype, request, and session bean scopes in Spring with practical failure examples.

Freshworks · Full Stack Developer · 3-4-years · technical

Published

Year not specified · Java, Spring Boot, Software Engineering

Community answers

Posted by wasAsked editorial collection

Spring bean scopes control how many instances the container creates and how long they live. singleton (default) - One instance per Spring application context, shared by all threads and requests. - Must be thread-safe; should not hold request or user state. - Failure example: a @Service with a field private User currentUser set per request. Under load, concurrent requests overwrite it, so one user's data appears in another user's response — a serious data leak. Fix: pass data as method parameters or use a request-scoped bean. prototype - A new instance every time the bean is requested from the container. - Spring does not manage its full lifecycle: destruction callbacks (@PreDestroy) are not called, so you must release resources yourself. - Failure example: injecting a prototype bean into a singleton with @Autowired creates the prototype only once, when the singleton is created — the "new instance each time" expectation silently fails. Fix: inject ObjectProvider<T> (or Provider<T>) and call getObject() when needed, use @Lookup methods, or a scoped proxy. request (web applications) - One instance per HTTP request. - Failure example: injecting a request-scoped bean into a singleton without a proxy fails at startup ("Scope 'request' is not active for the current thread"), or accessing it from a background thread or @Async method fails because there is no active request. Fix: use proxyMode = ScopedProxyMode.TARGET_CLASS (or @RequestScope, which uses a proxy by default), and copy needed data before handing work to other threads. session (web applications) - One instance per HTTP session. - Failure examples: storing large objects in session-scoped beans increases memory use per user and breaks horizontal scaling unless sessions are shared (Spring Session with Redis); session-scoped beans must be serializable for session replication; concurrent requests from the same user (several tabs) can modify session state simultaneously. Other scopes: application (one per ServletContext) and websocket. Guidelines - Keep most beans stateless singletons. - Use request scope for per-request context (tenant or correlation ID) only through proxies, or pass context explicitly. - Avoid session scope in stateless REST APIs; prefer tokens and external state stores. - Be careful with thread hand-offs (@Async, CompletableFuture, virtual threads): request-scoped beans and ThreadLocal context do not propagate automatically.

Ravindra Wadile · · 0 likes

Sign in to add your answer

Related interview topics