Bean Scopes in Spring: Singleton, Prototype, Request, Session

Day 03 – Bean Scopes (Singleton vs Prototype vs Request vs Session) What is Bean Scope? Bean Scope defines: • How many instances of a bean Spring creates • How long the bean lives By default, Spring creates only one object per bean. ==================================== Singleton (Default Scope) ==================================== Only ONE object is created for the entire application. @Component public class StudentService { } Spring creates one StudentService object and shares it everywhere. Memory efficient Best for stateless services Used in most backend applications In real projects: Controllers, Services, Repositories → Mostly Singleton ===================================== Prototype Scope ===================================== Every time the bean is requested → New object is created. @Component @Scope("prototype") public class StudentService { } Used when: • Object holds state • You need independent instances Not very common in REST APIs, but useful in specific cases. ======================================= Request Scope (Web Applications) ======================================= One bean per HTTP request. Each client request gets a new object. Used when: • You need request-specific data • Temporary processing per request ==================================== Session Scope ==================================== One bean per user session. Each logged-in user gets a separate object. Used when: • Storing user-specific session data Why This Matters in Real Backend Systems? Because scope : • Memory usage • Performance • Thread safety • Scalability ================================== Today’s Learning Spring does not just create objects. Understanding Bean Scope helps you think like a backend engineer. Tomorrow: Types of Dependency Injection (Constructor vs Setter vs Field) #Java #SpringBoot #SpringFramework #BackendDevelopment #Microservices #LearningInPublic

To view or add a comment, sign in

Explore content categories