Bean Scopes in Spring Framework: Complete Deep Dive
In the Spring Framework, Bean Scope defines how many physical instances of a bean Spring should create, and exactly how long those objects should survive inside the Inversion of Control (IOC) Container.
This is a massively important architecture topic because getting the scope wrong directly impacts:
- Memory Usage (Creating too many objects crashes the heap)
- Performance (Constantly creating heavy objects slows the CPU)
- Concurrency & Thread Safety (Shared state causes silent data corruption)
1. What is Bean Scope?
Consider a simple service class:
Question: How many EmployeeService objects will Spring physically create in memory?
Answer: It depends entirely on the declared Scope.
2. Singleton Scope (The Default)
Standard Definition
Singleton scope instructs Spring to create exactly one instance of a bean per IOC Container. This single instance is cached and shared across the entire application.
Because it is the default scope, both of these declarations do exactly the same thing:
Internal Backend Cache: `singletonObjects`
When the application starts, Spring scans the classes, instantiates the singleton bean exactly once, and stores it in an internal memory map called singletonObjects (which lives inside the DefaultSingletonBeanRegistry class).
Whenever a Controller requests the EmployeeService, Spring doesn't create a new object. It simply fetches the existing object from the singletonObjects cache and returns its memory reference.
The Thread Safety Problem
Because there is only one object shared across the entire application, multiple HTTP request threads will execute methods on that exact same object simultaneously.
If your Singleton bean contains state (instance variables), you will suffer fatal Race Conditions. Therefore, Singleton beans should always be entirely Stateless.
3. Prototype Scope
Standard Definition
A new, completely fresh bean instance is created every single time the bean is requested from the container.
When you call context.getBean(Employee.class) three times, Spring will execute the new Employee() constructor three separate times, returning Object A, Object B, and Object C. The singletonObjects cache is completely bypassed.
Important Interview Point: Destruction Management
For Prototype beans, Spring manages the creation and initialization (including @PostConstruct). However, Spring does NOT manage destruction.
Once Spring hands you a prototype bean, it forgets about it. The @PreDestroy method will never be executed for a prototype bean. The JVM Garbage Collector handles the cleanup.
4. Web-Aware Scopes (Request, Session, Application)
These scopes are only available in Web Applications (Spring MVC / Spring WebFlux).
Request Scope
Creates one object per HTTP Request. Once the request is fully processed and the response is sent, the bean is destroyed.
Real Example: Storing a parsed JWT token, Request ID, or temporarily authenticated user info for the lifecycle of a single API call.
Session Scope
Creates one object per HTTP Session. The bean survives across multiple requests from the exact same user, but is isolated from other users.
Real Example: Storing products in a user's shopping cart. User A gets Cart A, User B gets Cart B.
Application Scope
Creates one bean per ServletContext. It is essentially identical to a Singleton, but it operates at the Servlet container level rather than the Spring ApplicationContext level.
5. Singleton vs Prototype (The Ultimate Comparison)
| Feature | Singleton | Prototype |
|---|---|---|
| Default Scope? | Yes | No |
| Objects Created | Exactly One | Many (One per request) |
| Cache Used? | Yes (singletonObjects) |
No |
| Memory Usage | Very Low | High |
| Performance | Extremely Fast | Slower (repeated object creation) |
| Thread Safety | Dangerous (Must be stateless) | Safe (No shared state) |
| Destroy Managed? | Yes (by Spring) | No (by Garbage Collector) |
6. The Most Asked Interview Question
Q: What happens when you inject a Prototype Bean into a Singleton Bean?
Many developers think: "Because the injected bean is a Prototype, every time I call a method on the Service, it will use a brand new Prototype instance."
This is entirely WRONG.
Consider this setup:
The Reality: The EmployeeService is a Singleton. It is created only once at application startup. Therefore, its dependencies are injected only once.
Spring creates one single Employee prototype, injects it into the EmployeeService, and stops. From that point on, the Singleton Service will hold onto that exact same Prototype instance forever.
The Solution: ObjectProvider
If you genuinely need a fresh Prototype instance every time a method is called inside a Singleton, you must inject an ObjectProvider:
7. Complete Backend Working Flow Diagram
If an interviewer asks you to map the internal architectural flow of Bean Scopes, use this diagram:
Comments
Post a Comment