Spring Bean Scopes Cheat Sheet
Bean Scopes Overview
| Scope | Description | Example Usage |
|---|---|---|
| Singleton | Default scope; a single instance per Spring IoC container. | @Bean public MyBean myBean() { return new MyBean(); } |
| Prototype | Creates a new instance each time a bean is requested. | @Bean @Scope("prototype") public MyBean myBean() { return new MyBean(); } |
| Request | A new bean instance is created for each HTTP request. | @RequestScope public MyBean myBean() { return new MyBean(); } |
| Session | A new bean instance is created for each HTTP session. | @SessionScope public MyBean myBean() { return new MyBean(); } |
| Application | A singleton instance per ServletContext; shared across the entire application. | @ApplicationScope public MyBean myBean() { return new MyBean(); } |
| Websocket | A new bean instance is created for each WebSocket session. | @Scope(value = "websocket", proxyMode = ScopedProxyMode.TARGET_CLASS) public MyBean myBean() { return new MyBean(); } |
Conclusion
Understanding bean scopes is essential for managing the lifecycle and visibility of beans in a Spring application. This cheat sheet summarizes the key scopes and their usage.
Top comments (0)