Bean Scopes
Singleton, Prototype, Request, Session, Application scopes and scoped proxies
- Configure bean scopes with @Scope
- Inject a prototype-scoped bean into a singleton using scoped proxy
- Know which scope is appropriate for stateful vs stateless beans
@PostConstruct → use → @PreDestroy → destroy), as well as Dependency Injection. Bean Scope determines how many instances of a bean exist and when they're created — but the underlying construction/injection/post-construct sequence for each individual instance still follows the same lifecycle covered earlier. If those topics aren't clear yet, review them first.Table of Contents
- What Is Bean Scope?
- Singleton Scope
- Prototype Scope
- Request Scope
- Proxy Mode — Injecting a Request-Scoped Bean into a Singleton
- Session Scope
- Application Scope
- Comparison Table of All Scopes
- Practice Questions
- Summary
What Is Bean Scope?
Overview
Bean Scope defines how many instances of a given bean the Spring IOC container creates, and under what conditions/lifetime each instance exists. There are five types of bean scope in Spring:
- Singleton
- Prototype
- Request
- Session
- Application
Definition
Bean Scope
is a configuration that tells the Spring IOC container the cardinality (how many instances) and lifetime (when created, how long it lives) of a bean.
Why This Concept Exists
Not every object in an application should behave the same way in terms of instance count and lifetime. Some objects (like a shared configuration or service) should exist exactly once for the whole application. Others (like a form object that captures user-specific input) need a fresh instance every single time they're requested. Some need to be tied to the lifetime of a single web request, and others to an entire user session. Bean Scope gives developers fine-grained control over exactly this behavior, rather than forcing every bean to behave identically.
Internal Working Why the Bean Lifecycle Matters Here
@PostConstruct) is essential to understanding scope, because scope essentially controls when, in relation to the application/request/session timeline, this lifecycle sequence gets triggered for a given class — and how many times it gets triggered.Diagrams
Related Concepts
- Bean Lifecycle (construction, dependency injection,
@PostConstruct,@PreDestroy) - Dependency Injection (
@Autowired) - Eager vs. Lazy Initialization
Singleton Scope
Overview
Singleton is the default scope in Spring — if you don't explicitly specify a scope on a bean, it is automatically treated as Singleton.
Definition
Singleton scope
means only one instance is created per IOC container (in practice, since most applications run a single IOC container, this effectively means one instance per application).
Why This Concept Exists
Many objects in an application — services, repositories, shared configuration, utility beans — don't need or benefit from having multiple copies. Creating a single shared instance saves memory and ensures consistent shared state (where appropriate) across the entire application.
Internal Working Eager Initialization
This directly connects to the general eager-vs-lazy discussion from the bean lifecycle: Singleton is the scope that qualifies a bean for eager initialization by default.
Syntax
Implicit (default) Singleton — no annotation needed:
1@RestController2public class TestController1 {3
4 @GetMapping("/fetchUser")5 public String fetchUser() {6 return "user fetched";7 }8}Explicit Singleton — using the ConfigurableBeanFactory enum constant:
1@RestController2@Scope(ConfigurableBeanFactory.SCOPE_SINGLETON)3public class TestController2 {4}Explicit Singleton — using a plain string:
1@Component2@Scope("singleton")3public class User {4}Syntax Breakdown
| Element | Meaning |
|---|---|
@Scope(...) | Explicitly declares the scope of the bean |
ConfigurableBeanFactory.SCOPE_SINGLETON | An enum-like constant that internally just resolves to the string "singleton" |
"singleton" (plain string) | Equivalent to using the constant — both work identically |
(No @Scope at all) | Defaults to Singleton automatically |
@Scope entirely (relying on the default), use the ConfigurableBeanFactory.SCOPE_SINGLETON constant, or use the plain string "singleton" directly. All three produce identical behavior — internally, the constant is just a String value.Code Examples
Setup — Two Singleton-scoped controllers sharing one Singleton-scoped dependency:
1@RestController2public class TestController1 {3
4 @Autowired5 private User user;6
7 public TestController1() {8 System.out.println("TestController1 instance initialization");9 }10
11 @PostConstruct12 public void init() {13 System.out.println("TestController1 object hashCode: " + this.hashCode());14 System.out.println("User object hashCode: " + user.hashCode());15 }16}1@RestController2public class TestController2 {3
4 @Autowired5 private User user;6
7 public TestController2() {8 System.out.println("TestController2 instance initialization");9 }10
11 @PostConstruct12 public void init() {13 System.out.println("TestController2 object hashCode: " + this.hashCode());14 System.out.println("User object hashCode: " + user.hashCode());15 }16}1@Component2public class User {3 public User() {4 System.out.println("User initialization");5 }6}TestController1 instance initialization User initialization TestController1 object hashCode: <hash-A> User object hashCode: <hash-U> TestController2 instance initialization TestController2 object hashCode: <hash-B> User object hashCode: <hash-U> <-- SAME as above
Step-by-Step Execution
- Application starts → IOC container invoked.
- IOC scans and finds
TestController1(@RestController, effectively a@Component) — since Singleton is eagerly initialized, its constructor runs immediately →"TestController1 instance initialization"prints. At this point, the bean is constructed but its dependency is not yet injected. - IOC now resolves
TestController1's dependency: theuserfield. It checks if aUserbean already exists — it does not, so IOC constructs it →"User initialization"prints. Userhas no further dependencies, so it proceeds straight to@PostConstruct— theUserbean is now fully constructed, with some hash code (e.g.,).- The newly constructed
Userobject is injected intoTestController1'suserfield. TestController1has no more unresolved dependencies, so its own@PostConstructruns — printing bothTestController1's hash code and the injectedUser's hash code.- IOC then finds
TestController2, also Singleton and eagerly initialized → its constructor runs →"TestController2 instance initialization"prints. - IOC resolves
TestController2'suserdependency. This time, aUserbean already exists in the container (created in step 3) — sinceUseris Singleton, IOC reuses the same existing instance rather than creating a new one. - The same
Userobject (same hash code,) is injected intoTestController2. TestController2's@PostConstructruns, printing its own hash code and the (same)Userhash code.
Memory Representation
| Concept | Behavior Under Singleton Scope |
|---|---|
Number of heap objects created for User | Exactly one, for the entire application/IOC container lifetime |
| Reference sharing | Every class that @Autowireds a User receives a reference to the same heap object |
| Timing of creation | At application startup (eager initialization), assuming no @Lazy override |
Key Observations
- Only one instance is ever created per IOC container, no matter how many other beans depend on it.
- Once created, the same object is reused/injected everywhere that bean type is required.
- When you later invoke an API endpoint (e.g.,
fetchUser), no new object construction happens — everything was already constructed at startup; the API call simply invokes existing, already-wired objects. - Singleton beans are, by default, eagerly initialized at application startup (though this can still be overridden with
@Lazy, as covered in the bean lifecycle guide).
Best Practices
- Use Singleton (the default) for stateless services, shared configuration, repositories, and utility beans — anything that doesn't need per-request or per-user-specific state.
- Avoid storing mutable, request-specific, or user-specific state inside a Singleton bean's fields, since that state would be shared (and potentially corrupted) across all usages of the bean throughout the whole application.
Interview Notes
- Q: What is the default bean scope in Spring? → Singleton.
- Q: Is Singleton scope tied to the number of times a bean is
@Autowiredelsewhere? → No — regardless of how many classes depend on it, exactly one instance is created and shared. - Q: Are Singleton beans eagerly or lazily initialized by default? → Eagerly initialized (unless explicitly marked
@Lazy).
Prototype Scope
Overview
Prototype scope is essentially the opposite of Singleton in terms of instance count: a brand-new object is created every single time the bean is requested.
Definition
Prototype scope
means a new object is created each and every time the bean is requested — whether that request comes from a different class or the same class asking again. It is also, importantly, lazily initialized — never created at application startup, only when actually needed/requested.
Why This Concept Exists
Some objects genuinely need to be independent, fresh instances every time they're used — for example, objects representing a specific unit of work, a specific calculation, or any object where sharing state across usages would be incorrect or unsafe. Prototype scope exists for exactly these cases.
Syntax
1@Component2@Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE)3public class User {4 public User() {5 System.out.println("User initialization");6 }7}Or equivalently, using a plain string:
1@Component2@Scope("prototype")3public class User {4}Syntax Breakdown
| Element | Meaning |
|---|---|
@Scope(...) | Declares the bean's scope |
ConfigurableBeanFactory.SCOPE_PROTOTYPE / "prototype" | Both are equivalent ways of specifying prototype scope |
Internal Working Lazy Initialization
Code Examples
Setup:
1@RestController2@Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE)3public class TestController1 {4
5 @Autowired6 private User user;7
8 @Autowired9 private Student student;10
11 public TestController1() {12 System.out.println("TestController1 instance initialization");13 }14
15 @GetMapping("/fetchUser")16 public String fetchUser() {17 return "fetched";18 }19}1@Component2@Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE)3public class User {4 public User() {5 System.out.println("User initialization");6 }7}1@Component // no explicit scope --> defaults to Singleton2public class Student {3
4 @Autowired5 private User user;6
7 public Student() {8 System.out.println("Student instance initialization");9 }10
11 @PostConstruct12 public void init() {13 System.out.println("Student object hashCode: " + this.hashCode());14 System.out.println("User object hashCode: " + user.hashCode());15 }16}Student instance initialization User initialization Student object hashCode: <hash-S> User object hashCode: <hash-U1>
TestController1 prints nothing at startup — since it's Prototype-scoped, it is never eagerly constructed. Similarly, if User were referenced only by TestController1, it too would print nothing at startup. User prints here only because Student (a Singleton, eagerly initialized) also depends on it, forcing its construction at startup regardless of its own prototype-ness — because it is needed right then.Step-by-Step Execution — Application Startup
- IOC finds
TestController1— sees it's Prototype scope → lazily initialized → skips creating it now. - IOC finds
User— also Prototype scope → lazily initialized → skips creating it now (on its own, in isolation). - IOC finds
Student— Singleton scope (default, no@Scopespecified) → eagerly initialized → constructs it now →"Student instance initialization"prints. - IOC resolves
Student's dependency:user. SinceUseris genuinely required right now (to satisfyStudent's construction), IOC constructs aUserinstance at this point →"User initialization"prints, despiteUseritself being marked Prototype. Userhas no dependencies, so its@PostConstructruns (implicitly) — it's now fully constructed with hash code.- This
Userinstance is injected intoStudent. Student's@PostConstructruns, printing its own hash code () and the injectedUser's hash code ().- Application startup completes —
TestController1was never touched, since nothing required it yet.
Now — Hitting the fetchUser API Endpoint (First Call):
Output:
1TestController1 instance initialization2User initializationStep-by-Step Execution
- Since
TestController1is Prototype scope, IOC must construct a brand-new instance to service this request →"TestController1 instance initialization"prints. - IOC resolves
TestController1's dependencies. First,user: sinceUseris Prototype, a brand-newUserinstance is constructed here as well — even though aUserobject was already constructed earlier (and injected intoStudent), Prototype scope means every single request for aUserbean produces a fresh instance. So"User initialization"prints again, and this newUserobject has a different hash code () than the one injected intoStudent(). - Next,
student: sinceStudentis Singleton, the already-existingStudentinstance (created at startup, hash code) is simply reused/injected — no new construction happens. TestController1's dependencies are now resolved (a freshUser, and the existingStudent), and the request completes.
Hitting the fetchUser API a Second Time:
Since TestController1 is Prototype, another brand-new instance is constructed for this second call as well — you would see "TestController1 instance initialization" print yet again, along with another fresh User instance being constructed (since User is also Prototype).
Key Observations
- Prototype beans are never eagerly constructed at startup, regardless of anything else.
- However, a Prototype bean can still be constructed at startup indirectly — if a Singleton (eagerly initialized) bean depends on it, that dependency must be resolved right then, forcing construction at that moment, even though the bean's own scope is Prototype.
- Every time a Prototype-scoped bean is genuinely requested/needed — whether during startup dependency-resolution or in response to an explicit request like an API call — a completely new instance is created, evidenced by a different hash code each time.
- A Singleton bean injected as a dependency of a Prototype bean (or vice versa) still behaves according to its own scope rules — a Singleton stays the same single shared instance regardless of how many times a Prototype bean around it gets recreated.
Common Mistakes
Interview Notes
- Q: Is a Prototype bean ever created at application startup? → Only indirectly — if some eagerly-initialized (Singleton) bean has a hard dependency on it, forcing its construction to satisfy that dependency. On its own, Prototype is always lazy.
- Q: If you call the same API endpoint (backed by a Prototype-scoped controller) twice, how many controller instances get created? → Two — one for each individual call, since Prototype always constructs a fresh instance per request.
Request Scope
Overview
Request scope creates exactly one new object per HTTP request. This is one of the scopes most prone to developer confusion, largely because of the interaction with something called proxy mode, covered in its own section below.
Definition
Request scope
means a new object is created for each individual HTTP request. If, within processing that single HTTP request, the same bean type is needed multiple times, it is not recreated multiple times — the same instance is reused for the duration of that one request. It is lazily initialized.
Why This Concept Exists
Some data is naturally scoped to a single web request — for example, request-specific context, a request-tracking ID, or request-specific parsed data. Request scope allows Spring to automatically manage such objects, giving each incoming HTTP request its own isolated instance without the developer manually tracking request boundaries.
Syntax
1@RestController2@Scope(value = WebApplicationContext.SCOPE_REQUEST)3public class TestController1 {4}1@Component2@Scope(value = WebApplicationContext.SCOPE_REQUEST)3public class User {4}Syntax Breakdown
| Element | Meaning |
|---|---|
@Scope(value = WebApplicationContext.SCOPE_REQUEST) | Declares the bean to be created fresh once per HTTP request |
(or the string "request") | Equivalent literal value |
Code Examples
Setup:
1@RestController2@Scope(value = WebApplicationContext.SCOPE_REQUEST)3public class TestController1 {4
5 @Autowired6 private User user;7
8 @Autowired9 private Student student;10
11 public TestController1() {12 System.out.println("TestController1 instance initialization");13 }14
15 @GetMapping("/fetchUser")16 public String fetchUser() {17 return "fetched";18 }19}1@Component2@Scope(value = WebApplicationContext.SCOPE_REQUEST)3public class User {4 public User() {5 System.out.println("User initialization");6 }7}1@Component2@Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE)3public class Student {4
5 @Autowired6 private User user;7
8 public Student() {9 System.out.println("Student instance initialization");10 }11}(nothing printed — no beans constructed at startup)
Step-by-Step Execution — Application Startup
- IOC finds
TestController1— scope is Request → lazily initialized → nothing constructed now. - IOC finds
Student— scope is Prototype → also lazily initialized → nothing constructed now. - IOC finds
User— scope is Request → also lazily initialized → nothing constructed now. - Since nothing depends on anything else at startup time in a way that forces construction (unlike the earlier Singleton-depends-on-Prototype scenario), no objects are constructed at all during application startup.
Hitting fetchUser for the First Time (First HTTP Request):
Output:
1TestController1 instance initialization2User initialization3Student instance initializationStep-by-Step Execution
- An HTTP request arrives at
/fetchUser. SinceTestController1is Request-scoped, IOC constructs a new instance specifically for this request →"TestController1 instance initialization"prints. - IOC resolves dependencies. First,
user:Useris also Request-scoped. Since noUserobject exists yet for this particular request, IOC constructs one now →"User initialization"prints. ThisUserinstance is now considered "the"Userfor the remainder of this specific HTTP request. - Next,
student:Studentis Prototype-scoped — regardless of request boundaries, a new instance is always created →"Student instance initialization"prints. - IOC resolves
Student's own dependency onUser. SinceUseris Request-scoped, and aUserinstance was already created for this request (in step 2), IOC reuses that same instance rather than creating another one. - Result: within this single HTTP request, both
TestController1andStudentend up sharing the exact sameUserinstance — because Request scope guarantees one instance per request, not one instance per injection point.
Hitting fetchUser a Second Time (Second, New HTTP Request):
Output:
1TestController1 instance initialization2User initialization3Student instance initializationStep-by-Step Execution
- A new HTTP request arrives. Since
TestController1is Request-scoped, a brand-new instance is constructed for this new request (different from the one created for the first request) → prints again. Useris Request-scoped, and since this is a new request, noUserinstance yet exists for this request (the previous request'sUserinstance is irrelevant here) → a newUserinstance is constructed.Studentis Prototype-scoped → a new instance is constructed regardless (as always).Student's dependency onUseris resolved using the sameUserinstance created in step 2 for this current request — again, one shared instance within this request.
Key Observations
- Within a single HTTP request, if the same Request-scoped bean type is needed by multiple different classes, only one instance is created and shared across all of them for that request.
- Across different HTTP requests, each request gets its own, independent instance of any Request-scoped bean.
- Request scope is always lazily initialized — never created at application startup on its own.
Diagrams
Proxy Mode Injecting a Request-Scoped Bean into a Singleton
Overview
This is described as the point where "a lot of confusion happens" — what occurs when a Singleton-scoped bean has a dependency on a Request-scoped bean.
The Problem
Consider:
1@RestController2public class TestController1 { // Singleton (default, no scope specified)3
4 @Autowired5 private User user; // Request scoped6
7 public TestController1() {8 System.out.println("TestController1 instance initialization");9 }10}1@Component2@Scope(value = WebApplicationContext.SCOPE_REQUEST)3public class User {4 public User() {5 System.out.println("User initialization");6 }7}Why This Fails
TestController1 is Singleton → eligible for eager initialization → it begins constructing it immediately. It then tries to resolve TestController1's dependency on user. Since User is scoped to an HTTP request, and there is no active HTTP request during application startup (the application is just starting — no client request is in progress), Spring cannot construct or bind a User instance to satisfy this dependency. This causes bean creation to fail, and the application throws an error at startup.Internal Working The Root Cause
Request scope is fundamentally tied to the lifetime of an HTTP request. Eager initialization (which Singleton triggers by default) happens at application startup — a point in time where, by definition, no HTTP request yet exists. This creates a fundamental timing conflict: the Singleton wants its dependency resolved now (at startup), but the Request-scoped dependency can only meaningfully exist during an actual HTTP request, which hasn't happened yet.
The Solution Proxy Mode
Definition
Proxy Mode
tells Spring: "At the time of eager initialization (e.g., application startup), even though there's no active HTTP request, create a placeholder proxy object instead of the real one, and use that for the dependent bean's construction. Only when the proxy is actually invoked/used (during a real HTTP request) will the real, request-bound object be created and delegated to."
Syntax
1@Component2@Scope(value = WebApplicationContext.SCOPE_REQUEST, proxyMode = ScopedProxyMode.TARGET_CLASS)3public class User {4 public User() {5 System.out.println("User initialization");6 }7}Syntax Breakdown
| Element | Meaning |
|---|---|
proxyMode = ScopedProxyMode.TARGET_CLASS | Tells Spring to generate a CGLIB-based proxy standing in for the real User class, usable even outside an active HTTP request |
Code Examples
Startup Behavior With Proxy Mode:
Output:
1TestController1 instance initialization2TestController1 object hashCode: <hash-A>3User object hashCode: <some-proxy-hash>"User initialization" line prints at startup. This is the key signal that a dummy/proxy object was inserted in place of the real User instance — the real constructor never actually ran.Step-by-Step Execution — Application Startup With Proxy Mode
- IOC begins constructing
TestController1(Singleton, eager) →"TestController1 instance initialization"prints. - IOC attempts to resolve the
userdependency.Useris Request-scoped, but this time it's also configured withproxyMode = ScopedProxyMode.TARGET_CLASS. - Since there's no active HTTP request, but proxy mode is enabled, Spring creates a dummy proxy object standing in for the real
Userbean, and injects that proxy intoTestController1. TestController1's dependency is now considered "resolved" (with the proxy standing in), so its@PostConstructruns successfully — printing its own hash code and the proxy's hash code (not a real, constructedUserobject's hash code).- Bean creation for
TestController1succeeds — the earlier failure is avoided.
Hitting an API Endpoint That Actually Uses user (an actual HTTP Request):
Output:
1User initializationStep-by-Step Execution
- A real HTTP request now arrives, and code inside
TestController1actually invokes a method onuser(the proxy). - At this exact moment, the proxy internally delegates to constructing the real
Userobject, now properly bound to this actual HTTP request →"User initialization"prints for the first time. - The real, request-bound
Userobject is used to service this request.
Key Observations
- Proxy mode only defers the real object's creation — it doesn't eliminate Request scope's fundamental one-per-request behavior; it simply allows a Singleton to hold a stable reference (the proxy) that safely delegates to the real, per-request object only when actually invoked.
- The clearest way to detect whether a proxy (rather than a real object) was injected is to check whether the constructor's print statement (
"User initialization") actually executed at that point in time — if it's missing, a proxy was used instead. - Proxy mode is specifically the mechanism that resolves the "Singleton depends on Request-scoped bean" timing conflict.
Common Mistakes
@Autowired a Request-scoped (or Session-scoped) bean directly into a Singleton bean without configuring proxyMode will cause the application to fail at startup, because there is no active HTTP request (or session) to bind the dependency to during eager Singleton initialization.Best Practices
- Whenever a Singleton bean needs a Request-scoped (or Session-scoped) dependency, always configure
proxyMode = ScopedProxyMode.TARGET_CLASSon that dependency to avoid startup failures.
Interview Notes
- Q: Why does injecting a Request-scoped bean into a Singleton bean fail without proxy mode? → Because Singleton beans are eagerly initialized at application startup, at which point no HTTP request exists yet to bind the Request-scoped bean to.
- Q: What does
proxyMode = ScopedProxyMode.TARGET_CLASSactually do? → It causes Spring to inject a proxy object in place of the real bean at eager-initialization time; the real, request-bound object is only constructed later, when the proxy is actually invoked during a genuine HTTP request.
Session Scope
Overview
Session scope is conceptually very similar to Request scope, but tied to the lifetime of an entire HTTP session rather than a single HTTP request.
Definition
Session scope
means one object is created per HTTP session. A single HTTP session can span many individual HTTP requests — the same Session-scoped bean instance is reused across all of them, for as long as that session remains active (i.e., until it expires or is explicitly invalidated).
Why This Concept Exists
Some data genuinely needs to persist across multiple requests made by the same user during one continuous visit — for example, a shopping cart, login/authentication context, or any per-user state that should survive across multiple page loads/API calls but should not persist forever (only for the duration of that session).
Internal Working
- Session scope is lazily initialized, just like Request scope.
- Typically, an HTTP session is created the first time a user accesses an endpoint.
- A session remains active until it expires or is explicitly invalidated (e.g., via logout).
- Session expiry timing can be configured — the lecture specifically mentions checking a property resembling
server.servlet.session.timeoutinapplication.properties, though it notes there is some default expiry time Spring uses if you don't configure one explicitly.
Syntax
1@RestController2@Scope(value = WebApplicationContext.SCOPE_SESSION)3public class TestController1 {4
5 @Autowired6 private User user; // Singleton7
8 public TestController1() {9 System.out.println("TestController1 instance initialization");10 }11
12 @PostConstruct13 public void init() {14 System.out.println("TestController1 object hashCode: " + this.hashCode());15 System.out.println("User object hashCode: " + user.hashCode());16 }17}1@Component // no scope specified --> Singleton2public class User {3 public User() {4 System.out.println("User initialization");5 }6}Code Examples & Step-by-Step Execution
Application Startup:
TestController1is Session-scoped → lazily initialized → nothing constructed yet.Useris Singleton (default) → eagerly initialized → constructed immediately →"User initialization"prints, along with its hash code (from@PostConstruct, if defined onUseritself, or simply upon construction).
First Call to fetchUser (Creates a New HTTP Session):
Output:
1TestController1 instance initialization2TestController1 object hashCode: <hash-T1>3User object hashCode: <hash-U> (same as at startup)Step-by-Step Execution
- This is the first request, so a new HTTP session is created along with it.
- Since no
TestController1instance exists yet for this new session, IOC constructs one now →"TestController1 instance initialization"prints. - IOC resolves the
userdependency. SinceUseris Singleton, the already-existing instance (created at startup) is reused/injected — no new construction. TestController1's@PostConstructruns, printing its own hash code and the (unchanged, shared)Userhash code.
Calling fetchUser Again (Same, Still-Active Session):
Output:
1(no new instance-initialization prints — nothing new is constructed)Step-by-Step Execution
- The HTTP session created during the first call is still active (has not expired or been invalidated).
- Since this is merely a new HTTP request within the same, still-valid session, and
TestController1is Session-scoped (not Request-scoped), no new object is created — the existingTestController1instance for this session is simply reused directly. The API just executes normally, with no additional bean construction logging.
Calling a logout Endpoint That Ends the Session:
1@GetMapping("/logout")2public String logout(HttpServletRequest request) {3 HttpSession session = request.getSession();4 session.invalidate(); // manually ending the session for demonstration5 return "logged out";6}HttpServletRequest/HttpSession purely to make the session-ending behavior clearly observable. In real applications, session expiry is often handled automatically via configuration/timeout rather than manual invalidation.Calling fetchUser Again After Logout (New Session Now Required):
Output:
1TestController1 instance initialization2TestController1 object hashCode: <hash-T2> (different from before)3User object hashCode: <hash-U> (SAME as always - Singleton)Step-by-Step Execution
- Since the previous session was ended (invalidated) via the logout call, this new
fetchUsercall causes a brand-new HTTP session to be created. - Because
TestController1is Session-scoped, and there is no existing instance tied to this new session, IOC constructs a newTestController1instance →"TestController1 instance initialization"prints again, with a different hash code from the one created for the previous (now-ended) session. Userremains Singleton, so the exact sameUserinstance (created once, at application startup) is reused — its hash code never changes throughout the entire application's lifetime.
Key Observations
- Within the same active HTTP session, regardless of how many individual HTTP requests occur, the same Session-scoped bean instance is reused.
- A new session (whether it's the very first one, or a new one created after a previous session ends) results in a new instance being constructed for any Session-scoped bean.
- Session scope is, like Request scope, always lazily initialized.
- A Singleton dependency injected into a Session-scoped bean behaves exactly as expected for Singleton — always the same shared instance, completely unaffected by session creation/expiry.
Related Concepts
server.servlet.session.timeout(or similarly named property) inapplication.properties— used to configure how long a session remains valid before automatically expiring.- Proxy Mode — the same proxy-mode mechanism used for Request scope applies equally if a Singleton bean needs to depend on a Session-scoped bean, for the same underlying reason (no active session exists at application startup).
Interview Notes
- Q: What's the key difference between Request scope and Session scope? → Request scope creates a new instance per individual HTTP request; Session scope creates a new instance per HTTP session, which can span many HTTP requests.
- Q: Does calling the same endpoint twice within the same session create two Session-scoped bean instances? → No — as long as the session remains valid, the same instance is reused across multiple requests within that session.
Application Scope
Overview
Application scope is very similar to Singleton, but with one key distinction relating to multiple IOC containers.
Definition
Application scope
means one object is shared across multiple IOC containers — as opposed to Singleton, which guarantees only one object within a single IOC container.
Internal Working Singleton vs. Application
| Scope | Guarantee |
|---|---|
| Singleton | One object per IOC container |
| Application | One object shared across multiple IOC containers (e.g., if three separate IOC containers — IOC1, IOC2, IOC3 — were all running simultaneously, Application scope would ensure they all share the exact same single object) |
Key Observations
Best Practices
- Application scope is primarily relevant in multi-module or multi-context setups where more than one Spring IOC container genuinely coexists within the same running application — a comparatively rare architectural pattern.
- For the vast majority of standard Spring Boot applications (which run a single IOC container), Singleton and Application scope behave effectively identically — so there is rarely a practical reason to choose Application scope over the default Singleton.
Interview Notes
- Q: How does Application scope differ from Singleton scope? → Singleton guarantees one instance per IOC container; Application scope guarantees one instance shared across multiple IOC containers, when more than one exists.
- Q: Is Application scope commonly used in typical Spring Boot applications? → No — it's considered a rarely-needed scope in practice, since most applications run only a single IOC container, making it functionally indistinguishable from Singleton in those cases.
Comparison Table of All Scopes
| Scope | Instances Created | Initialization Timing | Lifetime Tied To | Needs Proxy Mode When Injected Into Singleton? |
|---|---|---|---|---|
| Singleton (default) | One per IOC container | Eager (by default) | Entire application/IOC container lifetime | N/A (it is the Singleton) |
| Prototype | New instance every single time requested | Lazy (always) | Not tracked/managed long-term by the container after creation | N/A — but injecting Prototype into Singleton means the Singleton only ever gets the one instance resolved at its own construction time |
| Request | New instance per HTTP request (shared within that one request) | Lazy (always) | Duration of a single HTTP request | ✅ Yes |
| Session | New instance per HTTP session (shared across many requests within that session) | Lazy (always) | Duration of an HTTP session (until expiry/invalidation) | ✅ Yes |
| Application | One instance shared across multiple IOC containers | Lazy | Lifetime spanning multiple IOC containers | Rarely relevant in practice |
Diagrams
Practice Questions
Easy
- What is the default scope in Spring, and is it eagerly or lazily initialized by default?
- Which scope creates a brand-new instance every single time the bean is requested?
- What is the main difference between Request scope and Session scope?
Medium
- Why does an application fail to start when a Singleton bean has an unmodified (no proxy mode)
@Autowireddependency on a Request-scoped bean? - If a Singleton bean (
Student) depends on a Prototype-scoped bean (User), and no other class ever separately requests aUserbean, willUserever be constructed at application startup? Why or why not? - Within one single HTTP request, if two different classes both
@Autowiredthe same Request-scoped bean, how many instances of that bean are created for that request?
Hard
- Trace through, step-by-step, what happens when
proxyMode = ScopedProxyMode.TARGET_CLASSis applied to a Request-scoped bean that a Singleton depends on — describe exactly what gets injected at startup, and precisely when the real object finally gets constructed. - Explain why calling the same API endpoint twice within the same still-active HTTP session does not create a new instance of a Session-scoped controller, but calling it after the session has been invalidated (e.g., via logout) does.
- A Prototype-scoped bean is injected as a dependency into another Prototype-scoped bean, which is itself injected into a Singleton controller. Explain how many total distinct object-creation events would occur if the Singleton's dependency were resolved once at startup, versus if the Singleton itself were instead marked
@Lazyand only triggered at first use.
Summary
- Bean Scope controls how many instances of a bean are created and when, building directly on the fundamentals of the bean lifecycle and dependency injection. There are five scopes: Singleton, Prototype, Request, Session, and Application.
- Singleton (the default) — exactly one instance per IOC container; eagerly initialized by default at application startup; the same shared instance is injected everywhere it's required.
- Prototype — a brand-new instance every single time the bean is requested; always lazily initialized, though it can still be constructed at startup indirectly if an eagerly-initialized (Singleton) bean genuinely depends on it.
- Request — one new instance per HTTP request; reused across multiple injection points within that same request, but a fresh instance is created for each new request; always lazily initialized.
- Proxy Mode (
proxyMode = ScopedProxyMode.TARGET_CLASS) — required whenever a Singleton (or any eagerly-resolved bean) needs to depend on a Request- or Session-scoped bean; it injects a placeholder proxy at eager-initialization time and defers real object construction until the proxy is actually invoked during a genuine request/session. - Session — one new instance per HTTP session, reused across all requests within that same session, until the session expires or is explicitly invalidated (e.g., via logout); always lazily initialized; expiry can be configured (e.g., via a session-timeout property in
application.properties). - Application — one instance shared across multiple IOC containers (as opposed to Singleton's one-per-single-container guarantee); explicitly noted as a rarely-used scope in real-world practice, since most applications run only a single IOC container.
Mastery check
How well can you recall this?
Finished this lesson?