Spring Bean Scopes Cheat Sheet

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.

原文链接:Spring Bean Scopes Cheat Sheet

© 版权声明
THE END
喜欢就支持一下吧
点赞6 分享
评论 抢沙发

请登录后发表评论

    暂无评论内容