In Spring Framework, a bean scope defines the lifecycle and visibility of a bean in the Spring IoC container—basically how and when the bean is created and how many instances exist.
Common Bean Scopes in Spring
1. Singleton (default)
- Only one instance of the bean is created per Spring IoC container.
- All requests for the bean return the same instance.
@Component
@Scope("singleton") // optional, since it's the default
public class SingletonService {
public SingletonService() {
System.out.println("Singleton instance created");
}
}
Usage:
ApplicationContext context = new AnnotationConfigApplicationContext(AppConfig.class);
SingletonService s1 = context.getBean(SingletonService.class);
SingletonService s2 = context.getBean(SingletonService.class);
System.out.println(s1 == s2); // true (same instance)
2. Prototype
- A new instance is created every time the bean is requested.
@Component
@Scope("prototype")
public class PrototypeService {
public PrototypeService() {
System.out.println("Prototype instance created");
}
}
Usage:
ApplicationContext context = new AnnotationConfigApplicationContext(AppConfig.class);
PrototypeService p1 = context.getBean(PrototypeService.class);
PrototypeService p2 = context.getBean(PrototypeService.class);
System.out.println(p1 == p2); // false (different instances)
3. Request (only in web-aware Spring context)
- A new bean instance is created per HTTP request.
@Component
@Scope("request")
public class RequestScopedBean {
public RequestScopedBean() {
System.out.println("New request bean created");
}
}
Every HTTP request gets a new instance.
4. Session
- A new bean instance is created per HTTP session.
@Component
@Scope("session")
public class SessionScopedBean {
public SessionScopedBean() {
System.out.println("Session bean created");
}
}
Every user session has its own instance.
5. Application
- One instance per ServletContext (shared across all requests and sessions).
@Component
@Scope("application")
public class ApplicationScopedBean {
public ApplicationScopedBean() {
System.out.println("Application scope bean created");
}
}
6. WebSocket
- One instance per WebSocket session.
@Component
@Scope("websocket")
public class WebSocketScopedBean {
public WebSocketScopedBean() {
System.out.println("WebSocket bean created");
}
}
Quick Summary
Scope | Description | Example Use Case |
---|---|---|
Singleton | One instance per container (default) | Service beans, configuration |
Prototype | New instance per request | Stateful objects, temporary tasks |
Request | New instance per HTTP request | Request-specific data (e.g., form objects) |
Session | New instance per HTTP session | User session data |
Application | One instance per application (ServletContext) | Global counters, caches |
WebSocket | One instance per WebSocket session | WebSocket communication state |