Understanding Bean Scopes in the Spring Framework
Spring’s default bean scope is singleton, where a single instance is created per container and shared across all request. The framework supports several scopes to manage bean lifecycle and visibility.
- Singleton: The default scope; one instance per Spring IoC container.
- Prototype: A new insatnce is created on each request.
- Request: Exclusive to web applications; a new instance per HTTP request, valid only for that request.
- Session: Exclusive to web applications; a new instance per HTTP session, valid for the session’s duration.
- Application: Exclusive to web applications; one instance per ServletContext, shared across the entire application.
- WebSocket: Exclusive to web applications; an instance is tied to a WebSocket’s lifecycle.
To specify a non-default scope, use the scope attribute in @Bean or @Scope annotations:
@Bean
@Scope("prototype")
public DataProcessor dataProcessor() {
return new DataProcessorImpl();
}
Here, dataProcessor is prototype-scoped, so each injection or getBean() call yields a new DataProcessorImpl instance.
Singleton
A singleton bean is instantiated once per container:
@Configuration
public class AppConfig {
@Bean
@Scope("singleton") // Optional, as it is default
public LoggerService loggerService() {
return new LoggerServiceImpl();
}
}
Multiple calls to loggerService() return the same LoggerServiceImpl instance.
Prototype
Each request creates a new prototype bean:
@Configuration
public class AppConfig {
@Bean
@Scope("prototype")
public CacheManager cacheManager() {
return new CacheManagerImpl();
}
}
Every retrieval of cacheManager produces a fresh CacheManagerImpl.
Request
In web contexts, a request-scoped bean is created per HTTP request:
@Controller
@Scope("request")
public class RequestHandler {
// Bean valid only for the current request
}
Session
A session-scoped bean is tied to an HTTP session:
@Component
@Scope("session")
public class SessionData {
// Instance persists for the user’s session
}
Application
Application-scoped beans are singleton-like with in a ServletContext:
@Component
@Scope("application")
public class AppConfigData {
// Shared across the entire web application
}
WebSocket
WebSocket-scoped beans align with WebSocket lifecycle events:
@Component
@Scope("websocket")
public class SocketSession {
// Created per WebSocket connection and destroyed on close
}
For web-specific scopes (request, session, application), ensure Spring’s web modules are configured, such as via ContextLoaderListener in web.xml or Spring Boot auto-configuration.