Spring Boot Bean Scopes: Singleton vs Prototype

🚀 Day 10/100: Spring Boot From Zero to Production Topic: Bean Scopes 🧩 Remember when we talked about Beans in Java? Quick recap: Beans are just instances of your classes that live inside the Spring Container. Spring manages their lifecycle and handles Dependency Injection so you don't have to manually "new" them up every time. But there is a lot more to it than just creating them. We need to talk about Bean Scopes. 1. The Default: Singleton By default, all beans in Spring are Singletons. This means Spring creates the instance once and shares that same exact instance every single time it’s needed. For components like Services, Repositories, or Controllers, a single instance is perfect because they are usually stateless they just perform actions. 2. The Alternative: Prototype But what if a single instance isn't enough? What if your bean holds state-specific data or thread-specific info where one user's data shouldn't leak into another's? That’s where the Prototype scope comes in. With this, Spring creates a brand-new instance every time the bean is requested. ⚠️ Word of caution: Use this wisely! Creating too many prototype beans when they aren't needed can put a heavy load on your memory. 3. Web-Aware Scopes If you are building web apps, Spring offers even more specialized scopes: Request Scope: A new bean for every single HTTP request. Session Scope: A bean that lives as long as the user's HTTP session. Choosing the right scope is all about balancing memory efficiency with data integrity. How do you usually decide between Singleton and Prototype in your projects? Let’s discuss below! 👇 #Java #SpringBoot #SoftwareDevelopment #100DaysOfCode #Backend

  • No alternative text description for this image

To view or add a comment, sign in

Explore content categories