In Spring core, bean scopes determine the lifecycle and visibility of a bean instance. When a bean is defined, you can specify its scope, which controls how many instances of the bean are created and how long they live.
Here are the different bean scopes in Spring and their characteristics:
Singleton
This is the default scope in Spring. Only one instance of the bean is created and shared across the application context. Whenever a bean with a singleton scope is requested, the same instance is returned. This scope is suitable for beans that are stateless and thread-safe.
Example:
@Bean
public MyService myService() {
return new MyService();
}
Prototype
A new instance of the bean is created every time it is requested. This scope is useful for beans that maintain a state and must be different for each use.
Example:
@Bean
@Scope("prototype")
public MyService myService() {
return new MyService();
}
Request
A new instance of the bean is created for each HTTP request. This scope is suitable for beans that are used in web applications and need to be unique per request.
Example:
@Bean
@Scope(value = WebApplicationContext.SCOPE_REQUEST, proxyMode = ScopedProxyMode.TARGET_CLASS)
public MyService myService() {
return new MyService();
}
Session
A new instance of the bean is created for each HTTP session. This scope is useful for beans that need to maintain state across multiple requests from the same user.
Example:
@Bean
@Scope(value = WebApplicationContext.SCOPE_SESSION, proxyMode = ScopedProxyMode.TARGET_CLASS)
public MyService myService() {
return new MyService();
}
Global Session
This scope is similar to the session scope but is used in a clustered environment where the session data is replicated across multiple servers.
Example:
@Bean
@Scope(value = WebApplicationContext.SCOPE_GLOBAL_SESSION, proxyMode = ScopedProxyMode.TARGET_CLASS)
public MyService myService() {
return new MyService();
}
Application
Only one instance of the bean is created per ServletContext. This scope is useful for beans that are global to the entire application.
Example:
@Bean
@Scope(value = WebApplicationContext.SCOPE_APPLICATION, proxyMode = ScopedProxyMode.TARGET_CLASS)
public MyService myService() {
return new MyService();
}
Websocket
A new instance of the bean is created for each WebSocket session. This scope is useful for beans that need to maintain state across multiple WebSocket requests.
Example:
@Bean
@Scope(value = "websocket", proxyMode = ScopedProxyMode.TARGET_CLASS)
public MyService myService() {
return new MyService();
}
In addition to these standard scopes, Spring also allows you to define custom scopes if none of the standard scopes meet your needs.