Could you list and describe the different scopes used for beans in Spring?
sobes.tech AI
Answer from AI
In the Spring Framework, there are several scopes for beans that define the lifespan and visibility of bean instances:
-
singleton (default) — one instance of the bean is created for the entire Spring container. All requests to this bean receive the same object.
-
prototype — a new bean instance is created each time it is requested from the container.
-
request — the bean lives for the duration of a single HTTP request. Used in web applications, each HTTP request gets its own instance.
-
session — the bean lives for the duration of a user's HTTP session.
-
application — the bean lives within the ServletContext, i.e., within the scope of the entire web application.
-
websocket — the bean lives for the duration of a WebSocket session.
Example of declaring with a scope:
@Component
@Scope("prototype")
public class MyPrototypeBean {
// ...
}
The choice of scope depends on the requirements for the bean's lifecycle and state within the application.