Request and Session Scopes in Spring
Fast recall
Quick revision
Core answer
Whether you understand web-specific scopes and how they differ from singleton and prototype
Not knowing that proxyMode is required when injecting request or session scoped beans into singletons, causing startup errors
Give a realistic session example like a shopping cart and explain how the scoped proxy delegates to the current request or session instance
Interview-ready guide
Interview answer
Web scopes tie bean storage to web context state. A request-scoped RequestContext can hold request-specific data and is destroyed when that request completes. A session-scoped Cart can survive across requests in one HTTP session. Problems arise when a singleton is created at startup and asks for a bean whose real instance exists only during a request. @RequestScope and @SessionScope use proxy defaults that make this common injection work, or the singleton can inject ObjectProvider. Avoid storing large or sensitive mutable state in sessions without a clear lifetime and concurrency policy.
Request and Session Scopes in Spring
Direct Answer
Request scope creates one bean instance for one HTTP request; session scope creates one per HTTP session. Injecting either directly into a longer-lived singleton needs deferred lookup, commonly a scoped proxy or ObjectProvider, because the real request or session instance does not exist when the singleton is created. The proxy mode is a common solution, not an unconditional requirement for every use.
Common Mistakes & Pitfalls
- Forgetting proxyMode when injecting into singletons: The most common error. Without proxyMode=TARGET_CLASS, Spring throws a BeanCreationException at startup because it can't inject a shorter-lived bean into a longer-lived one. The proxy delays resolution until runtime.
- Using session scope for data that belongs in the database: Freshers store things like order history in session scope. Sessions expire, servers restart, and in a load-balanced setup session data might not replicate. Persistent data belongs in the database.
- Not invalidating sessions on logout: Session scoped beans live until you call HttpSession.invalidate(). If you don't, the old session can be hijacked or waste memory.
Check your understanding
Answer these without looking back at the article.
- Why is proxyMode required for web-scoped beans in singletons?
- What is ScopedProxyMode?
- Why wouldn't you use session scope in a stateless REST API?
Looking for a structured roadmap?
Every module on this page is also part of the full Java backend interview track.