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.

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Discover a treasure trove of wisdom within this insightful piece, highly respected in the nurturing DEV Community enviroment. Developers, whether novice or expert, are encouraged to participate and add to our shared knowledge basin.

A simple "thank you" can illuminate someone's day. Express your appreciation in the comments section!

On DEV, sharing ideas smoothens our journey and strengthens our community ties. Learn something useful? Offering a quick thanks to the author is deeply appreciated.

Okay