Spring Bean Scopes Explained: Singleton, Prototype, Request, Session, Application

🚀 Java Backend Interview Series – Question #75 Q75. What are Bean Scopes in Spring Framework? When working with Spring Framework / Spring Boot, one important concept that often comes up in interviews is: 👉 Bean Scope It defines: 👉 How many instances of a bean are created and how long they live Let’s break it down 👇 🔹 1️⃣ What is a Bean Scope? In Spring, a bean is an object managed by the Spring IoC container. Bean scope determines: ✔ Lifecycle of the bean ✔ Visibility of the bean ✔ Number of instances created 🔹 2️⃣ Types of Bean Scopes 🔸 Singleton (Default Scope) @Component @Scope("singleton") class MyService {} 📌 Characteristics: ✔ Only one instance per Spring container ✔ Shared across the entire application 👉 Most commonly used in backend systems 🔸 Prototype @Scope("prototype") class MyService {} 📌 Characteristics: ✔ New instance created every time requested ✔ Not managed after creation 👉 Use case: When you need independent objects 🔸 Request Scope (Web) @Scope("request") class MyService {} 📌 Characteristics: ✔ One instance per HTTP request 👉 Use case: Request-specific data 🔸 Session Scope (Web) @Scope("session") class MyService {} 📌 Characteristics: ✔ One instance per HTTP session 👉 Use case: User-specific data 🔸 Application Scope @Scope("application") class MyService {} 📌 Characteristics: ✔ One instance per ServletContext 🔹 3️⃣ Key Differences ScopeInstances CreatedUse CaseSingletonOneShared servicesPrototypeMultipleIndependent objectsRequestPer requestWeb request dataSessionPer sessionUser session dataApplicationPer appGlobal data🔹 4️⃣ Real-World Backend Insight ✔ Most beans in Spring Boot are Singleton ✔ Prototype is used for stateful objects ✔ Request/Session scopes are used in web applications 🔹 5️⃣ Important Concept 👉 Singleton in Spring ≠ Singleton Design Pattern Spring creates one instance per container, not per JVM. 🎯 Interview Tip A tricky question: 👉 “Is Spring Singleton thread-safe?” Answer: ❌ No by default ✔ It depends on how the bean is implemented 💬 Follow-up Interview Question What happens if a Prototype bean is injected into a Singleton bean? #Java #SpringBoot #SpringFramework #BeanScope #JavaDeveloper #BackendDevelopment #CodingInterview #TechInterview #SoftwareEngineering #Microservices #Programming #DeveloperCommunity #SystemDesign #CleanCode #IoC

  • No alternative text description for this image

To view or add a comment, sign in

Explore content categories