DEV Community

Code Green
Code Green

Posted on

1 1

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.

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay