Spring Bean Scopes Cheat Sheet

codegreen

Code Green

Posted on November 27, 2024

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.

πŸ’– πŸ’ͺ πŸ™… 🚩
codegreen
Code Green

Posted on November 27, 2024

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related