🚀 Spring Framework 🌱 | Day 4 Spring Bean Scopes Made Simple (with Real-Life Examples) Understanding bean scopes in Spring is very important for writing efficient applications. Let’s break it down in a simple way 👇 👉 1. Singleton (Default Scope) Only one object is created for the entire application. 🏠 Real-life example: Think of it like a TV in your home – everyone uses the same TV. In Spring, all requests use the same bean instance. 👉 2. Prototype A new object is created every time it is requested. ☕ Real-life example: Ordering coffee at a café – every time you order, you get a new cup. In Spring, each request gets a fresh bean. 👉 3. Request Scope (Web apps only) One object per HTTP request. 🧾 Real-life example: Filling a form online – each request has its own data. Once the request ends, the object is gone. 👉 4. Session Scope One object per user session. 🛒 Real-life example: Shopping cart in an e-commerce app – items stay until you logout or session expires. 💡 Quick Summary: 👉 Singleton → One shared object 👉 Prototype → New object every time 👉 Request → One per HTTP request 👉 Session → One per user session 🚀 Pro Tip: Use the right scope based on your use case to avoid performance and memory issues. #SpringFramework #Java #BackendDevelopment #InterviewPrep #SoftwareEngineering
Spring Bean Scopes Explained: Singleton, Prototype, Request, Session
More Relevant Posts
-
𝗦𝘁𝗼𝗽 𝘂𝘀𝗶𝗻𝗴 @ComponentScan 𝗳𝗼𝗿 𝘀𝗵𝗮𝗿𝗲𝗱 𝗺𝗼𝗱𝘂𝗹𝗲𝘀.⚡️ Your shared libraries should be 𝗽𝗹𝘂𝗴-𝗮𝗻𝗱-𝗽𝗹𝗮𝘆, not a guessing game of which beans are being scanned. 👉 The fix? 𝗔𝘂𝘁𝗼-𝗰𝗼𝗻𝗳𝗶𝗴𝘂𝗿𝗮𝘁𝗶𝗼𝗻. Clean. Predictable. Zero setup. I wrote a quick guide on how to do it right in Spring Boot 👇 https://lnkd.in/dAu6mrtG #SpringBoot #Beans #Java #Kotlin #SoftwareArchitecture
To view or add a comment, sign in
-
🧠 After exploring singleton and prototype, I discovered a very practical Spring Boot scope today 👀 Request Scope 🌐 Here’s the simple idea 👇 ✅ A new bean object is created for every HTTP request ✅ Different requests never share the same object ✅ Perfect for request-specific processing This makes it super useful for 👇 🔹 request tracing IDs 🔹 temporary request metadata 🔹 audit logging helpers 🔹 request-level user context The cleanest way to use it 👇 @RequestScope 💡 My takeaway: Scope is not just about memory — it directly shapes how safely your web app handles request data ⚡ #Java #SpringBoot #RequestScope #BackendDevelopment #LearningInPublic
To view or add a comment, sign in
-
-
Ever started your Spring Boot app and seen a lot of logs fly by? Lets understand it : 1. Spring Boot Banner You’ll first see the ASCII banner showing your Spring Boot version: :: Spring Boot :: (v3.3.4) It confirms your app's running version and JVM details. 2. Startup Info Example: Starting DemoApplication using Java 21 on LAPTOP with PID 4523 This line shows the main class, Java version, and process ID. 3. Active Profiles If you see: The following profiles are active: dev it means Spring is loading application-dev.yml (useful for environment-based configs). 4. Application Context Initialization Spring Boot begins creating the ApplicationContext, scanning for components, configurations, and auto-configurations: Refreshing org.springframework.boot.web.servlet.context.AnnotationConfigServletWebServerApplicationContext 5. Auto-Configuration Phase Spring Boot uses AutoConfiguration classes to wire beans automatically : Tomcat initialized with port(s): 8080 (http) Use --debug or --trace to view which auto-configs were applied or skipped. 6. Bean Creation and Initialization You’ll notice logs like: Initializing Spring DispatcherServlet 'dispatcherServlet' This means your web layer is ready to handle requests. 7. Web Server Startup Depending on the stack, you will see: Tomcat for Spring MVC Netty for WebFlux Example: Tomcat started on port(s): 8080 (http) with context path '' 8. Startup Metrics Spring Boot 3.x includes StartupStep metrics for better visibility into startup performance (visible when Actuator is enabled). 9. Application Ready Finally, you will see something like: Started DemoApplication in 2.345 seconds (JVM running for 2.789) This means the context has fully loaded and your app is live. Want to see this in real time , Run your app with: java -jar app.jar --debug to get a detailed auto-configuration report and startup sequence , extremely useful for debugging startup issues and also understand what is really happening when you start the app. #SpringBoot #Java
To view or add a comment, sign in
-
🚀 Day 18/100: Spring Boot From Zero to Production Topic: Auto-Configuration 💡 What is Auto-Configuration? One of the most powerful features in Spring Boot Turns hours of setup into minutes Eliminates heavy XML configs and manual bean wiring ⏳ Before Auto-Configuration Manually define multiple beans Write hundreds of lines of XML Configure everything yourself → painful ⚙️ What Happens Now? Your @SpringBootApplication kicks things off Spring Boot scans the classpath Looks for dependencies like: spring-webmvc spring-data-jpa 👉 Presence/absence of JARs = signals 🧠 Behind the Scenes Reads a special file: META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports Contains hundreds of auto-config classes Each uses conditions like: @ConditionalOnClass @ConditionalOnMissingBean 👉 Result: Beans get configured automatically 🌐 Simple Example Add: spring-boot-starter-web Spring Boot assumes: You need a web app So it adds an embedded server (Tomcat) automatically 🛠️ Can You Override It? YES You can: Define your own beans Override defaults Disable auto-config if needed Auto-configuration isn’t magic. It’s just smart defaults + conditional logic working for you #Java #SpringBoot #SoftwareDevelopment #100DaysOfCode #Backend
To view or add a comment, sign in
-
-
🚀 #Day11 – JSP Session Tracking Today I explored JSP Session Tracking and how web applications remember user data across multiple pages 🔄 💡 What I Learned: In web apps, HTTP is stateless → it doesn’t remember user info by default Using Session Tracking, we can store and maintain user data (like name, email) across pages 🛠️ My Practice Task: Created a form to take Name & Email as input After submitting, the data is stored in a session object Then redirected to tutorial pages like: Java ☕ Python 🐍 Spring 🌱 📌 How It Works: User enters details in form JSP stores data using session.setAttribute() Data is available on all pages using session.getAttribute() User navigates between tutorial pages without losing data ✨ Key Concepts: Session object in JSP setAttribute() & getAttribute() Maintaining user state across multiple pages Real-time use case: Login systems, shopping carts 🛒 🔥 Mini Insight: Session tracking makes web applications user-friendly and dynamic, because it keeps user data intact while navigating! #Java #JSP #SessionTracking #WebDevelopment #FullStackDeveloper #LearningJourney #100DaysOfCode 🚀 Saketh Kallepu,Uppugundla Sairam,Anand Kumar Buddarapu
To view or add a comment, sign in
-
💡 application.properties vs application.yml – Configuration Styles in Spring Boot Choosing the right configuration format in Spring Boot can impact both readability and maintainability of your application. Here’s a concise comparison 🔹 application.properties A traditional key-value format widely used across Spring applications. Example: server.port=8080 spring.datasource.url=jdbc:mysql://localhost:3306/mydb spring.datasource.username=root spring.datasource.password=1234 ✔ Simple and familiar ✔ Easy to get started ✔ Suitable for smaller configurations 🔹 application.yml A YAML-based format that supports hierarchical structuring. Example: server: port: 8080 spring: datasource: url: jdbc:mysql://localhost:3306/mydb username: root password: 1234 ✔ Cleaner and more readable for complex setups ✔ Reduces repetition through nesting ✔ Better suited for large-scale applications Key Comparison AspectpropertiesymlStructureFlat (key-value)HierarchicalReadabilityModerateHigh (for complex)MaintenanceSlightly harderEasier at scaleLearning CurveMinimalRequires YAML basics⚡ Recommendation Use .properties for simple or quick configurations Use .yml when working with structured, multi-level configurations Both formats are fully supported by Spring Boot and can be used interchangeably based on team preference and project needs. #SpringBoot #Java #SoftwareEngineering #Backend #ConfigurationManagement
To view or add a comment, sign in
-
-
📘 #Day113 of My Java Full Stack Journey Today I learned about the Servlet Life Cycle, which explains how a servlet is created, used, and destroyed by the web container (Tomcat). ✨ 𝐒𝐞𝐫𝐯𝐥𝐞𝐭 𝐋𝐢𝐟𝐞 𝐂𝐲𝐜𝐥𝐞: Servlet life cycle defines the stages a servlet goes through from loading to destruction These stages are managed by the Servlet Container (Tomcat). There are three main life cycle methods: 1️⃣𝐢𝐧𝐢𝐭() This method is called only once when the servlet is loaded for the first time. ➜ It is used to perform initialization tasks like: ▪ Loading configuration ▪ Creating database connections ▪ Allocating resources ➜ Before calling init(), the servlet container first loads the servlet class and creates its object. 𝑬𝒙: public void init() throws ServletException 2️⃣𝐬𝐞𝐫𝐯𝐢𝐜𝐞() This method handles client requests. Each time a request comes from the browser, the service() method is executed. ➜ In HttpServlet, service() internally calls: ▪ doGet() ▪ doPost() based on request type. 𝑬𝒙: public void service(ServletRequest request, ServletResponse response) 3️⃣ 𝐝𝐞𝐬𝐭𝐫𝐨𝐲() This method is called only once when the servlet is removed from memory. ➜ It is used to: ▪ Close database connections ▪ Release resources ▪ Perform cleanup operations 𝑬𝒙: public void destroy() 📌 𝐊𝐞𝐲 𝐋𝐞𝐚𝐫𝐧𝐢𝐧𝐠𝐬 ▪ Servlet life cycle is managed by Tomcat ▪ init() runs only once during initialization ▪ service() handles every client request ▪ destroy() runs before servlet removal Gurugubelli Vijaya Kumar | 10000 Coders #Java #Servlets #ServletLifecycle #ApacheTomcat #JavaWebDevelopment #BackendDevelopment
To view or add a comment, sign in
-
-
🚀 What really happens when you run a Spring Boot application? Most developers use: 👉 SpringApplication.run(App.class, args); …but few understand what happens behind the scenes. Here’s a clear breakdown: 🔹 1. Bootstrapping Starts The JVM calls main(), and Spring Boot begins initialization. 🔹 2. Environment Setup Loads application.properties / application.yml, environment variables, and profiles. 🔹 3. ApplicationContext Creation Spring creates the IoC container to manage all beans. 🔹 4. Component Scanning Detects @Component, @Service, @Repository, @RestController and registers them. 🔹 5. Auto-Configuration Based on dependencies, Spring Boot configures components automatically (MVC, JPA, etc.). 🔹 6. Embedded Server Startup Starts embedded Apache Tomcat—no external installation needed. 🔹 7. DispatcherServlet Initialization Registers the front controller to handle all incoming HTTP requests. 🔹 8. Bean Initialization & Dependency Injection All beans are created and wired using DI. 🔹 9. Application Ready ✅ Your app is now ready to handle requests. 💡 Key Takeaway: SpringApplication.run() is not just a method—it bootstraps the entire application, sets up the container, auto-configures components, and starts the web server. #Java #SpringBoot #BackendDevelopment #Microservices #Programming #SoftwareEngineering #TechLearning
To view or add a comment, sign in
-
-
🚀 What Really Happens When You Hit an API in Spring Boot? (Most beginners skip this — don't be one of them!) When I first started using Spring Boot, I knew how to write an API — but I had no idea what happened the moment I hit that endpoint. Turns out, there's an entire journey happening behind the scenes. Here's the full flow, broken down simply 👇 🔹 Tomcat — The Gatekeeper Every request first lands on the embedded Tomcat server. It listens on port 8080 and receives the raw HTTP request before anything else. 🔹 DispatcherServlet — The Front Controller This is the real entry point of Spring MVC. One servlet handles every single request and decides where it needs to go — like a receptionist routing calls across an office. 🔹 Handler Mapping — The Directory DispatcherServlet doesn't guess. It asks Handler Mapping — which controller owns this URL and HTTP method? 🔹 Interceptor — The Security Check Before your code even runs, interceptors handle cross-cutting concerns — authentication, logging, rate limiting. 🔹 Controller → Service → Repository — The Layers You Already Know The request flows through your layered architecture exactly the way we discussed last time. Controller routes, Service processes, Repository fetches. 🔹 Jackson — The Translator On the way back, Jackson silently converts your Java object into JSON. No extra code needed. 🔹 Response — Back to the Client Clean JSON, delivered. 💡 The biggest shift for me? Realizing that even a simple GET /users/1 triggers an entire coordinated flow — and Spring Boot handles most of it invisibly, so you can focus on what matters. #SpringBoot #Java #BackendDevelopment #SoftwareEngineering #JavaDeveloper #SpringFramework #APIDesign #CodingJourney
To view or add a comment, sign in
-
-
🚀 Day 7 — What is Bean? (Core Spring Concept 🔥) Today I understood one important thing… 👉 Everything in Spring is a Bean 💡 What is a Bean? 👉 A Bean is an object created and managed by Spring (IoC container) (Simple: Spring creates object, we just use it) ⚙️ How Spring Creates Bean? Using XML (<bean>) Using Annotations (@Component, @Service) 👉 Spring container creates, manages, and injects beans ⚡ Bean Scope (Important 🔥) 🔹 Singleton (default) 👉 Only ONE object created 🔹 Prototype 👉 New object every time 🔍 Bean Lifecycle (Simple Flow) 👉 Create → Initialize → Use → Destroy 💡 One line I learned: 👉 In Spring, objects are called Beans and Spring manages them 💬 Which scope confused you — Singleton or Prototype? Day 7 done ✅ #Spring #Java #BackendDevelopment #LearningInPublic #30DaysOfCode #SpringBoot #Developers
To view or add a comment, sign in
-
More from this author
Explore content categories
- Career
- Productivity
- Finance
- Soft Skills & Emotional Intelligence
- Project Management
- Education
- Technology
- Leadership
- Ecommerce
- User Experience
- Recruitment & HR
- Customer Experience
- Real Estate
- Marketing
- Sales
- Retail & Merchandising
- Science
- Supply Chain Management
- Future Of Work
- Consulting
- Writing
- Economics
- Artificial Intelligence
- Employee Experience
- Workplace Trends
- Fundraising
- Networking
- Corporate Social Responsibility
- Negotiation
- Communication
- Engineering
- Hospitality & Tourism
- Business Strategy
- Change Management
- Organizational Culture
- Design
- Innovation
- Event Planning
- Training & Development