Spring Bean Scopes
- In Spring Framework, bean scopes define the lifecycle and visibility of beans in the Spring IoC container.
@Scopedefines a bean's lifecycle and visibility of the bean.
Common @Scope Values
-
singleton( by default)
- Only one instance of the bean per Spring container.
- Same object is shared everywhere.
- This is the default scope if no other scope is specified.
Lifecycle: The bean is created when the application context is initialized and destroyed when the context is destroyed.
-
prototype
- A new instance is created every time the bean is requested.9
Lifecycle: Created every time requested, not managed by Spring after that.
-
request (Web-aware only)
- One bean instance per HTTP request.
- Used in web applications (Spring MVC).
Lifecycle: Created for each HTTP request, destroyed at request end
-
session(Web-aware only)
- One bean instance per HTTP session.
lifecycle: Created for each HTTP session, destroyed when session ends
-
application (Web-aware only)
- One bean instance per ServletContext (entire web app).
- Similar to singleton but specific to web context.
Lifecycle: Created when ServletContext is initialized, destroyed at shutdown.
-
websocket(Web-aware only, since Spring 4.2)
- One bean instance per WebSocket session.
Lifecycle: Created when WebSocket session is established, destroyed at session end
Example:
Points to remember
- @Scope is applied at the class level.
- Affects the Spring-managed bean, not the class itself.
- Each bean (even from the same class) can have a different scope.
- Does not apply globally to the class — only to the specific bean definition.
Example Code
@Configuration
public class AppConfig {
@Bean
@Scope("singleton") // First bean with singleton scope
public MyBean singletonBean() {
// This scope applies only to the Spring-managed bean of singletonBean
return new MyBean();
}
@Bean
@Scope("prototype") // Second bean with prototype scope
public MyBean prototypeBean() {
// This scope applies only to the Spring-managed bean of prototypeBean
return new MyBean();
}
}
Github Code : Bean Scope : Spring