In Spring Framework, bean scopes define the lifecycle and visibility of a bean. The scope determines how and when a bean is instantiated, used, and destroyed.
Singleton (Default Scope):
- Description: Only one instance of the bean is created per Spring IoC container, and the same instance is shared across the application.
- When to use: For stateless beans or beans that are shared across the application.
- Example:
@Bean @Scope("singleton") // Optional, as this is the default scope. public MyBean myBean() { return new MyBean(); }- Note: Even in a multithreaded application, only one instance of the bean will exist.
Prototype:
- Description: A new instance of the bean is created every time it is requested from the Spring IoC container.
- When to use: For stateful or non-shared beans where each client needs its own instance.
- Example:
@Bean @Scope("prototype") public MyBean myBean() { return new MyBean(); }- Note: The container does not manage the complete lifecycle of prototype-scoped beans (e.g., no
@PreDestroycallback).
Request (Web Applications):
- Description: A single instance of the bean is created for each HTTP request. It is available for the duration of the request.
- When to use: For request-scoped beans in web applications.
- Example:
@Bean @Scope("request") public MyBean myBean() { return new MyBean(); }- Note: This scope works only in a web-aware Spring ApplicationContext.
Session (Web Applications):
- Description: A single instance of the bean is created for each HTTP session.
- When to use: For beans that need to maintain session-specific data.
- Example:
@Bean @Scope("session") public MyBean myBean() { return new MyBean(); }- Note: This scope also requires a web-aware ApplicationContext.
Application (Web Applications):
- Description: A single instance of the bean is created for the lifecycle of a
ServletContext. - When to use: For beans that need to share global data across all sessions and requests.
- Example:
@Bean @Scope("application") public MyBean myBean() { return new MyBean(); }
WebSocket (WebSocket Applications):
- Description: A single instance of the bean is created for the lifecycle of a WebSocket.
- When to use: For beans that maintain state specific to a WebSocket session.
- Example:
@Bean @Scope("websocket") public MyBean myBean() { return new MyBean(); }
Summary of Scopes:
| Scope | Description | Usage Context |
|---|---|---|
| Singleton | One instance per Spring IoC container | Default scope |
| Prototype | New instance per request to the container | Stateful beans |
| Request | One instance per HTTP request | Web applications |
| Session | One instance per HTTP session | Web applications |
| Application | One instance per ServletContext | Web applications |
| WebSocket | One instance per WebSocket lifecycle | WebSocket applications |
Understanding and choosing the right bean scope is crucial for building efficient and scalable Spring applications.