Week 2 Day 4 — Bean Scopes: Singleton, Prototype, Request, Session, and Scoped Proxy
Goal
Today I want to understand Spring bean scopes.
Main questions:
- What is a bean scope?
- What is the default bean scope?
- What does singleton mean in Spring?
- Is Spring singleton the same as Java Singleton pattern?
- What is prototype scope?
- What is request scope?
- What is session scope?
- What happens when a prototype bean is injected into a singleton bean?
- What is
ObjectProvider? - What is a scoped proxy?
- What are common exam traps?
1. Quick Review from Day 3
In Day 3, I learned:
- Profiles control which configuration and beans are active.
application-dev.ymlloads only whendevis active.@Profile("dev")means the bean is active only in thedevprofile.@Profile("!prod")means the bean is active whenprodis not active.- Multiple profiles can be active at the same time.
- Profiles are for environment-level differences.
Memory sentence:
Profiles control which beans and configuration are active.
Today I learn about bean scopes.
2. What Is a Bean Scope?
A bean scope defines:
How long a Spring bean lives and how many instances Spring creates.
Simple questions a scope answers:
Does Spring create one object?
Does Spring create a new object every time?
Does Spring create one object per HTTP request?
Does Spring create one object per HTTP session?
Simple definition:
A bean scope controls the lifecycle and visibility of a Spring bean instance.
3. Common Spring Bean Scopes
Common scopes:
| Scope | Meaning |
|---|---|
singleton | one bean instance per Spring container |
prototype | new bean instance every time requested |
request | one bean instance per HTTP request |
session | one bean instance per HTTP session |
application | one bean instance per ServletContext |
websocket | one bean instance per WebSocket session |
Most important for the exam:
singleton
prototype
request
session
4. Default Bean Scope
The default Spring bean scope is:
singleton
Example:
@Service
public class OrderService {
}
This is a singleton bean by default.
It means Spring creates one OrderService instance per Spring container.
Memory sentence:
The default bean scope in Spring is singleton.
5. What Does Singleton Mean in Spring?
Spring singleton means:
One bean instance per Spring IoC container.
Example:
@Service
public class OrderService {
}
Spring creates one instance:
ApplicationContext
└── orderService -> one OrderService object
If three controllers inject OrderService, they all receive the same bean instance.
6. Spring Singleton Example
@Service
public class OrderService {
}
@RestController
public class OrderController {
private final OrderService orderService;
public OrderController(OrderService orderService) {
this.orderService = orderService;
}
}
@RestController
public class AdminOrderController {
private final OrderService orderService;
public AdminOrderController(OrderService orderService) {
this.orderService = orderService;
}
}
Both controllers receive the same OrderService instance.
OrderController -> same OrderService bean
AdminOrderController -> same OrderService bean
7. Spring Singleton vs Java Singleton Pattern
This is a very important exam trap.
Spring Singleton
One bean instance per Spring container.
Java Singleton Pattern
Usually one instance per JVM, controlled by static access.
Java Singleton example:
public class AppConfig {
private static final AppConfig INSTANCE = new AppConfig();
private AppConfig() {
}
public static AppConfig getInstance() {
return INSTANCE;
}
}
Spring singleton is not the same.
Exam memory sentence:
Spring singleton means one bean instance per Spring container, not one instance per JVM.
8. Can There Be More Than One Spring Singleton Instance?
Yes.
If there are multiple Spring containers, each container can have its own singleton bean.
Example:
ApplicationContext 1 -> one OrderService
ApplicationContext 2 -> one OrderService
So Spring singleton is container-specific.
9. Singleton Beans Must Be Designed Carefully
Because singleton beans are shared, they should usually be stateless.
Good singleton service:
@Service
public class PriceCalculator {
public BigDecimal calculatePrice(Order order) {
return order.items().stream()
.map(Item::price)
.reduce(BigDecimal.ZERO, BigDecimal::add);
}
}
This is good because the method uses local variables and input parameters.
10. Bad Singleton Bean with Mutable State
Bad:
@Service
public class OrderService {
private Long currentOrderId;
public void process(Long orderId) {
this.currentOrderId = orderId;
// business logic
}
}
Problem:
OrderService is shared by many requests.
currentOrderId can be overwritten by another request.
This can cause race conditions and wrong data.
Singleton services should not store request-specific state in fields.
11. Good Singleton Rule
Good:
@Service
public class OrderService {
public void process(Long orderId) {
Long currentOrderId = orderId;
// use local variable
}
}
Memory sentence:
Singleton beans should usually be stateless.
12. Is Singleton Thread-Safe Automatically?
No.
Spring singleton does not automatically make your code thread-safe.
If a singleton bean has mutable shared state, multiple threads can access it at the same time.
Bad:
@Service
public class CounterService {
private int counter = 0;
public int increment() {
return ++counter;
}
}
This is not thread-safe.
Important:
Spring manages bean lifecycle, not your shared mutable state.
13. Prototype Scope
Prototype scope means:
Spring creates a new bean instance every time the bean is requested from the container.
Example:
@Component
@Scope("prototype")
public class ReportBuilder {
}
Every time Spring is asked for ReportBuilder, it creates a new object.
context.getBean(ReportBuilder.class) -> new ReportBuilder
context.getBean(ReportBuilder.class) -> another new ReportBuilder
context.getBean(ReportBuilder.class) -> another new ReportBuilder
14. Prototype Scope Example
@Component
@Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE)
public class JobContext {
private final UUID id = UUID.randomUUID();
public UUID getId() {
return id;
}
}
If I request it multiple times:
JobContext a = context.getBean(JobContext.class);
JobContext b = context.getBean(JobContext.class);
Then:
a != b
They are different instances.
15. Singleton vs Prototype
| Scope | Instance behavior |
|---|---|
| singleton | one instance per Spring container |
| prototype | new instance each time requested |
Example:
Singleton:
getBean() -> same object
getBean() -> same object
Prototype:
getBean() -> new object
getBean() -> new object
16. Prototype Lifecycle
This is important.
For singleton beans, Spring manages the full lifecycle:
create
inject dependencies
initialize
destroy on context shutdown
For prototype beans, Spring creates and initializes them, but does not manage destruction in the same way.
Important:
Spring does not automatically call destroy callbacks for prototype beans when the application context closes.
Memory sentence:
Spring creates prototype beans, but the caller is responsible for cleanup.
17. Prototype Bean Use Cases
Prototype scope can be useful for:
stateful helper objects
builders
temporary processing contexts
objects with short-lived state
Example:
@Component
@Scope("prototype")
public class CsvImportContext {
private int processedRows;
private int failedRows;
public void rowProcessed() {
processedRows++;
}
}
Each import job may need a fresh context.
18. The Big Trap: Prototype Injected into Singleton
This is one of the most important exam topics.
Example:
@Component
@Scope("prototype")
public class JobContext {
}
@Service
public class JobService {
private final JobContext jobContext;
public JobService(JobContext jobContext) {
this.jobContext = jobContext;
}
}
JobService is singleton.
JobContext is prototype.
Question:
Does
JobServiceget a newJobContextevery time a method is called?
Answer:
No.
Spring creates JobService once at startup.
At that time, Spring injects one JobContext.
After that, the same JobContext stays inside the singleton JobService.
19. Why Prototype-in-Singleton Is Tricky
Startup flow:
1. Spring creates singleton JobService.
2. JobService needs JobContext.
3. Spring creates one prototype JobContext.
4. Spring injects it into JobService.
5. JobService keeps that same instance forever.
So this is not dynamic:
@Service
public class JobService {
private final JobContext jobContext;
public void runJob() {
// same jobContext every time
}
}
Exam memory sentence:
A prototype bean injected into a singleton is created once at singleton creation time.
20. How to Get a Fresh Prototype from a Singleton
If a singleton bean needs a fresh prototype each time, use:
ObjectProvider<T>
Provider<T>
lookup method injection
scoped proxy
ApplicationContext getBean
Most practical and clean:
ObjectProvider<T>
21. Using ObjectProvider
@Service
public class JobService {
private final ObjectProvider<JobContext> jobContextProvider;
public JobService(ObjectProvider<JobContext> jobContextProvider) {
this.jobContextProvider = jobContextProvider;
}
public void runJob() {
JobContext jobContext = jobContextProvider.getObject();
// fresh prototype instance
}
}
Now each call to:
jobContextProvider.getObject()
requests a new prototype bean from Spring.
22. Why ObjectProvider Is Useful
ObjectProvider is useful for:
lazy dependency access
optional dependencies
getting fresh prototype instances
getting dependencies only when needed
accessing all beans of a type
Memory sentence:
ObjectProviderlets a singleton ask Spring for a dependency later.
23. Provider<T>
Java also has provider-style access.
Example:
@Service
public class JobService {
private final Provider<JobContext> jobContextProvider;
public JobService Provider<JobContext> jobContextProvider) {
this.jobContextProvider = jobContextProvider;
}
public void runJob() {
JobContext jobContext = jobContextProvider.get();
}
}
Conceptually similar:
Ask provider for a fresh dependency when needed.
For Spring-specific projects, ObjectProvider is common.
24. ApplicationContext Lookup
This also works:
@Service
public class JobService {
private final ApplicationContext applicationContext;
public JobService(ApplicationContext applicationContext) {
this.applicationContext = applicationContext;
}
public void runJob() {
JobContext jobContext = applicationContext.getBean(JobContext.class);
}
}
But this is usually less clean.
Why?
Because the service now depends directly on the Spring container.
Better:
ObjectProvider<JobContext>
Memory sentence:
Prefer
ObjectProviderover injectingApplicationContextfor prototype lookup.
25. Request Scope
Request scope is a web scope.
It means:
One bean instance per HTTP request.
Example:
@Component
@RequestScope
public class RequestContext {
private final String requestId = UUID.randomUUID().toString();
public String getRequestId() {
return requestId;
}
}
Each HTTP request gets its own RequestContext.
Request 1 -> RequestContext A
Request 2 -> RequestContext B
Request 3 -> RequestContext C
26. Request Scope Use Cases
Request-scoped beans can store request-specific data:
request ID
current tenant
request metadata
correlation ID
temporary request state
Example:
@Component
@RequestScope
public class TenantContext {
private String tenantId;
public String getTenantId() {
return tenantId;
}
public void setTenantId(String tenantId) {
this.tenantId = tenantId;
}
}
Important:
Request-specific state should not be stored in singleton services.
27. Session Scope
Session scope is also a web scope.
It means:
One bean instance per HTTP session.
Example:
@Component
@SessionScope
public class ShoppingCart {
private final List<String> items = new ArrayList<>();
public void addItem(String item) {
items.add(item);
}
public List<String> getItems() {
return items;
}
}
Each user session gets its own ShoppingCart.
User session A -> ShoppingCart A
User session B -> ShoppingCart B
28. Request vs Session Scope
| Scope | Lifetime |
|---|---|
| request | one HTTP request |
| session | one HTTP session |
Example:
Request scope:
new bean for each request
Session scope:
same bean for same user's session
Request scope is shorter.
Session scope is longer.
29. Web Scopes Require Web Context
Request and session scopes work in web-aware Spring applications.
If I try to use request scope in a non-web application, it may fail because there is no HTTP request.
Important:
Request and session scopes require a web application context.
30. Injecting Request Scope into Singleton
This is another important topic.
Most controllers and services are singleton by default.
Example:
@Service
public class AuditService {
private final RequestContext requestContext;
public AuditService(RequestContext requestContext) {
this.requestContext = requestContext;
}
}
AuditService is singleton.
RequestContext is request-scoped.
Question:
How can a singleton hold a request-scoped bean if the request changes every time?
Answer:
Spring usually injects a proxy.
31. What Is a Scoped Proxy?
A scoped proxy is a proxy object that stands in place of the real scoped bean.
The singleton receives the proxy.
At runtime, the proxy finds the correct bean for the current request or session.
Mental model:
AuditService singleton
-> RequestContext proxy
-> real RequestContext for current HTTP request
So the injected object is stable, but the target behind it changes per request.
32. Request Scope with Proxy
Example:
@Component
@Scope(value = WebApplicationContext.SCOPE_REQUEST, proxyMode = ScopedProxyMode.TARGET_CLASS)
public class RequestContext {
}
Or simpler:
@Component
@RequestScope
public class RequestContext {
}
@RequestScope is a composed annotation that commonly uses scoped proxy behavior.
33. Session Scope with Proxy
Example:
@Component
@SessionScope
public class ShoppingCart {
}
A singleton service can inject it because Spring can use a proxy.
Example:
@Service
public class CartService {
private final ShoppingCart shoppingCart;
public CartService(ShoppingCart shoppingCart) {
this.shoppingCart = shoppingCart;
}
}
The injected ShoppingCart may actually be a proxy that delegates to the session-specific cart.
34. Why Scoped Proxy Exists
Without proxy:
Singleton bean is created at startup.
Request bean exists only during an HTTP request.
At startup, no request exists.
So Spring cannot inject the real request bean directly.
With proxy:
Spring injects a proxy at startup.
During each request, the proxy delegates to the correct request-scoped object.
Memory sentence:
Scoped proxy lets a long-lived bean depend on a short-lived scoped bean.
35. Scope Annotations
Common annotations:
@Scope("singleton")
@Scope("prototype")
@RequestScope
@SessionScope
@ApplicationScope
Examples:
@Component
@Scope("prototype")
public class ReportBuilder {
}
@Component
@RequestScope
public class RequestContext {
}
@Component
@SessionScope
public class ShoppingCart {
}
36. Singleton Scope with @Scope
This is explicit but usually unnecessary:
@Component
@Scope("singleton")
public class OrderService {
}
Because singleton is already the default.
Most of the time:
@Service
public class OrderService {
}
is enough.
37. Prototype Scope with @Scope
Use:
@Component
@Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE)
public class ReportBuilder {
}
or:
@Component
@Scope("prototype")
public class ReportBuilder {
}
The constant is safer than a string.
38. Request Scope with @Scope
You may see:
@Component
@Scope(value = WebApplicationContext.SCOPE_REQUEST)
public class RequestContext {
}
or simply:
@Component
@RequestScope
public class RequestContext {
}
@RequestScope is easier to read.
39. Session Scope with @Scope
You may see:
@Component
@Scope(value = WebApplicationContext.SCOPE_SESSION)
public class ShoppingCart {
}
or simply:
@Component
@SessionScope
public class ShoppingCart {
}
40. Application Scope
Application scope means:
One bean instance per ServletContext.
Example:
@Component
@ApplicationScope
public class ApplicationStats {
}
This is a web application scope.
It is less commonly used than singleton.
Difference:
singleton = one per Spring container
application = one per ServletContext
In many simple apps, the difference is not very visible.
41. WebSocket Scope
WebSocket scope means:
One bean instance per WebSocket session.
This is less common for normal REST APIs.
For the exam, focus more on:
singleton
prototype
request
session
42. Real Example: Request ID
Request-scoped bean:
@Component
@RequestScope
public class RequestInfo {
private final String requestId = UUID.randomUUID().toString();
public String getRequestId() {
return requestId;
}
}
Service:
@Service
public class LoggingService {
private final RequestInfo requestInfo;
public LoggingService(RequestInfo requestInfo) {
this.requestInfo = requestInfo;
}
public void log(String message) {
System.out.println(requestInfo.getRequestId() + ": " + message);
}
}
Each request gets a different request ID.
43. Real Example: Tenant Context
For a multi-tenant app:
@Component
@RequestScope
public class TenantContext {
private String tenantId;
public String getTenantId() {
return tenantId;
}
public void setTenantId(String tenantId) {
this.tenantId = tenantId;
}
}
A filter can set tenant ID from a header:
X-Tenant-Id: tenant-123
Then services can access the tenant context during the request.
44. Be Careful with Request Context
Request-scoped data should be used carefully.
Do not hide too much business logic in request-scoped context.
Good use:
request ID
tenant ID
current request metadata
Bad use:
large business state
important domain data
database transaction state
Keep business logic in services.
45. Real Example: Shopping Cart
For traditional web apps:
@Component
@SessionScope
public class ShoppingCart {
private final List<Long> productIds = new ArrayList<>();
public void add(Long productId) {
productIds.add(productId);
}
public List<Long> getProductIds() {
return productIds;
}
}
Each user session has a separate cart.
For stateless REST APIs, session scope is less common.
46. Scopes and REST APIs
In modern REST APIs, many applications are stateless.
Common scopes:
singleton for services
singleton for repositories
request scope sometimes for request metadata
prototype rarely
session scope rarely
Spring services and repositories are usually singleton.
This is normal.
47. Scope and Thread Safety
Important rule:
Singleton beans can be used by many threads.
Therefore:
Do not store request-specific mutable state in singleton fields.
Good singleton field examples:
repository dependency
service dependency
configuration properties
Clock
ObjectMapper
PasswordEncoder
Bad singleton field examples:
currentUserId
currentRequest
currentOrderId
temporary calculation result
48. Real Exam Question: Default Scope
Question:
What is the default bean scope in Spring?
Answer:
The default bean scope is singleton.
49. Real Exam Question: Spring Singleton
Question:
What does singleton mean in Spring?
Answer:
Singleton means Spring creates one bean instance per Spring IoC container.
50. Real Exam Question: Spring Singleton vs Java Singleton
Question:
Is Spring singleton the same as Java Singleton pattern?
Answer:
No. Spring singleton means one bean instance per Spring container. Java Singleton pattern usually means one instance per JVM controlled by static access.
51. Real Exam Question: Prototype Scope
Question:
What does prototype scope mean?
Answer:
Prototype scope means Spring creates a new bean instance every time the bean is requested from the container.
52. Real Exam Question: Prototype Destruction
Question:
Does Spring manage the full destruction lifecycle of prototype beans?
Answer:
No. Spring creates and initializes prototype beans, but it does not automatically manage their destruction when the context closes. The caller is responsible for cleanup.
53. Real Exam Question: Prototype in Singleton
Question:
@Component
@Scope("prototype")
public class JobContext {
}
@Service
public class JobService {
private final JobContext jobContext;
public JobService(JobContext jobContext) {
this.jobContext = jobContext;
}
}
Does JobService receive a new JobContext every time a method is called?
Answer:
No. JobService is singleton, so Spring creates it once and injects one prototype JobContext at creation time. The same JobContext instance is reused inside that singleton.
54. Real Exam Question: Fresh Prototype
Question:
How can a singleton get a fresh prototype instance each time?
Answer:
Use ObjectProvider<T>, Provider<T>, lookup method injection, or request the bean from ApplicationContext. ObjectProvider<T> is usually a clean Spring-specific solution.
55. Real Exam Question: Request Scope
Question:
What does request scope mean?
Answer:
Request scope means Spring creates one bean instance per HTTP request.
56. Real Exam Question: Session Scope
Question:
What does session scope mean?
Answer:
Session scope means Spring creates one bean instance per HTTP session.
57. Real Exam Question: Scoped Proxy
Question:
Why do we need a scoped proxy?
Answer:
A scoped proxy allows a long-lived bean, such as a singleton service, to depend on a short-lived bean, such as a request-scoped bean. The singleton receives a proxy, and the proxy delegates to the correct real bean for the current request or session.
58. Real Exam Question: Stateful Singleton
Question:
Why is this dangerous?
@Service
public class UserService {
private Long currentUserId;
}
Answer:
UserService is singleton by default and shared across requests. currentUserId is mutable request-specific state. Multiple threads or requests can overwrite it, causing incorrect behavior. Singleton beans should usually be stateless.
59. Real Exam Question: Request Scope in Non-Web App
Question:
Can I use request scope in a non-web application?
Answer:
Request scope requires a web-aware context and an active HTTP request. In a non-web application, request scope usually does not make sense and may fail.
60. Interview Answer
Question:
What are bean scopes in Spring?
Good answer:
Bean scopes define how long a bean lives and how many instances Spring creates. The default scope is singleton, which means one bean instance per Spring container. Prototype scope creates a new bean instance each time it is requested. In web applications, request scope creates one bean per HTTP request, and session scope creates one bean per HTTP session.
61. Interview Answer
Question:
What is the difference between singleton and prototype scope?
Good answer:
Singleton scope means Spring creates one bean instance per application context and reuses it everywhere. Prototype scope means Spring creates a new bean instance every time the bean is requested from the container. Singleton is the default and is commonly used for services and repositories. Prototype is useful for stateful, short-lived objects.
62. Interview Answer
Question:
What happens when a prototype bean is injected into a singleton bean?
Good answer:
The prototype bean is created once when the singleton bean is created. The singleton then keeps that same prototype instance. It does not receive a new prototype every time a method is called. If the singleton needs a fresh prototype instance each time, it should use ObjectProvider, Provider, lookup method injection, or another lazy lookup mechanism.
63. Interview Answer
Question:
Why should singleton beans usually be stateless?
Good answer:
Singleton beans are shared across the whole Spring container and can be used by multiple threads or requests at the same time. If a singleton stores request-specific mutable state in fields, one request can overwrite data from another request. This can cause race conditions and incorrect behavior. Therefore, services and repositories should usually be stateless and keep request-specific data in method parameters, local variables, or request-scoped objects.
64. Interview Answer
Question:
What is a scoped proxy?
Good answer:
A scoped proxy is an object that Spring injects instead of the real scoped bean. It is useful when a long-lived bean, such as a singleton service, depends on a shorter-lived bean, such as a request-scoped or session-scoped bean. The proxy stays the same, but it delegates calls to the correct real bean for the current request or session.
65. Tiny Code Practice
Create a prototype bean:
@Component
@Scope("prototype")
public class ImportContext {
private final UUID id = UUID.randomUUID();
public UUID getId() {
return id;
}
}
Bad singleton usage:
@Service
public class ImportService {
private final ImportContext importContext;
public ImportService(ImportContext importContext) {
this.importContext = importContext;
}
public void runImport() {
System.out.println(importContext.getId());
}
}
Question:
Why is this not creating a new
ImportContextfor every import?
Answer:
Because ImportService is singleton. Spring creates it once and injects one prototype ImportContext at that time. The same instance is used for every method call.
Better:
@Service
public class ImportService {
private final ObjectProvider<ImportContext> importContextProvider;
public ImportService(ObjectProvider<ImportContext> importContextProvider) {
this.importContextProvider = importContextProvider;
}
public void runImport() {
ImportContext importContext = importContextProvider.getObject();
System.out.println(importContext.getId());
}
}
Now each import can get a fresh ImportContext.
66. Tiny Bug Practice
Problem:
@Service
public class CheckoutService {
private Long currentCustomerId;
public void checkout(Long customerId) {
this.currentCustomerId = customerId;
}
}
Question:
What is wrong?
Answer:
CheckoutService is singleton by default. The field currentCustomerId stores request-specific mutable state. If multiple users call this service at the same time, they can overwrite each other's data. Use method parameters or request-scoped context instead.
Better:
@Service
public class CheckoutService {
public void checkout(Long customerId) {
Long currentCustomerId = customerId;
// use local variable
}
}
Practice Questions and Answers
Question 1
What is a bean scope?
Answer:
A bean scope defines how long a Spring bean lives and how many instances Spring creates.
Question 2
What is the default bean scope in Spring?
Answer:
The default bean scope is singleton.
Question 3
What does singleton mean in Spring?
Answer:
Singleton means Spring creates one bean instance per Spring IoC container.
Question 4
Is Spring singleton the same as Java Singleton pattern?
Answer:
No. Spring singleton means one bean instance per Spring container. Java Singleton pattern usually means one instance per JVM controlled by static access.
Question 5
Why should singleton services usually be stateless?
Answer:
Singleton services should usually be stateless because they are shared across requests and threads. Mutable request-specific state in fields can cause race conditions and incorrect data.
Question 6
Is singleton scope automatically thread-safe?
Answer:
No. Singleton scope does not automatically make a bean thread-safe. Thread safety depends on how the bean is implemented.
Question 7
What does prototype scope mean?
Answer:
Prototype scope means Spring creates a new bean instance every time the bean is requested from the container.
Question 8
Does Spring manage prototype bean destruction automatically?
Answer:
No. Spring creates and initializes prototype beans, but it does not automatically manage their destruction when the context closes.
Question 9
What happens when a prototype bean is injected into a singleton bean?
Answer:
The prototype bean is created once when the singleton is created. The singleton keeps that same instance.
Question 10
How can a singleton get a fresh prototype bean each time?
Answer:
A singleton can get a fresh prototype using ObjectProvider<T>, Provider<T>, lookup method injection, or ApplicationContext.getBean().
Question 11
What is ObjectProvider useful for?
Answer:
ObjectProvider is useful for lazy dependency access, optional dependencies, and getting fresh prototype instances from a singleton.
Question 12
What does request scope mean?
Answer:
Request scope means one bean instance per HTTP request.
Question 13
What does session scope mean?
Answer:
Session scope means one bean instance per HTTP session.
Question 14
What is the difference between request scope and session scope?
Answer:
Request scope creates a new bean for each HTTP request. Session scope keeps one bean for the duration of a user's HTTP session.
Question 15
What is a scoped proxy?
Answer:
A scoped proxy is a proxy object injected in place of a scoped bean. It delegates calls to the correct real bean for the current scope.
Question 16
Why is a scoped proxy useful?
Answer:
A scoped proxy is useful when a long-lived bean, such as a singleton, depends on a short-lived bean, such as a request-scoped or session-scoped bean.
Question 17
Can request scope be used without a web request?
Answer:
Usually no. Request scope requires a web-aware context and an active HTTP request.
Question 18
What is wrong with storing currentUserId as a field in a singleton service?
Answer:
currentUserId is request-specific mutable state. Since the service is singleton and shared, multiple requests can overwrite the field and cause wrong behavior.
Question 19
Which scopes are most important for the certification?
Answer:
The most important scopes for certification are:
singleton
prototype
request
session
Question 20
Which scope is usually used for normal services and repositories?
Answer:
Normal services and repositories are usually singleton beans.
Final Memory Sentences
- A bean scope controls how long a bean lives and how many instances Spring creates.
- The default bean scope is singleton.
- Spring singleton means one bean instance per Spring container.
- Spring singleton is not the same as Java Singleton pattern.
- Singleton beans should usually be stateless.
- Singleton scope does not automatically make code thread-safe.
- Prototype scope creates a new bean each time it is requested.
- Spring does not automatically destroy prototype beans.
- A prototype injected into a singleton is created once at singleton creation time.
- Use
ObjectProviderwhen a singleton needs fresh prototype instances. - Request scope means one bean per HTTP request.
- Session scope means one bean per HTTP session.
- A scoped proxy lets a singleton depend on a request-scoped or session-scoped bean.
- Do not store request-specific mutable state in singleton service fields.