Junior
What scopes in Spring do you know?
sobes.tech AI
Answer from AI
Spring Framework defines several scopes for beans:
- Singleton: One instance of the bean is created for the Spring container. This is the default scope.
- Prototype: A new instance of the bean is created each time it is requested.
- Request: For web applications. One instance of the bean is created per HTTP request.
- Session: For web applications. One instance of the bean is created per HTTP session.
- Application: For web applications. One instance of the bean is created for the entire ServletContext.
- WebSocket: For WebSocket applications. One instance of the bean is created per WebSocket session.
- CustomScopes: Ability to define custom scopes.
Here is an example of declaring a bean with different scopes:
// Declaration of Singleton (default)
@Component
public class SingletonBean {
// ...
}
// Declaration of Prototype
@Component
@Scope("prototype")
public class PrototypeBean {
// ...
}
// Declaration of Request (for web applications)
@Component
@Scope("request")
public class RequestBean {
// ...
}
// Declaration of Session (for web applications)
@Component
@Scope("session")
public class SessionBean {
// ...
}
Difference between Singleton and Prototype:
| Property | Singleton | Prototype |
|---|---|---|
| Number of instances | One per container | New each request |
| Lifecycle management | By Spring container | By Spring container until creation, then user-managed |
| State | Shared state for all calls | Separate state for each instance |
Scopes Request, Session, Application, and WebSocket are only applicable in web applications and are managed by the respective request or session handlers.