🚀 Spring Boot Series #006 Spring Bean Lifecycle — The Hidden Magic Behind Your Application Ever wondered what really happens when your Spring Boot app starts? It’s not just objects being created… it’s a well-orchestrated lifecycle 🔄 Let’s break it down 👇 🔹 1. 𝗕𝗲𝗮𝗻 𝗜𝗻𝘀𝘁𝗮𝗻𝘁𝗶𝗮𝘁𝗶𝗼𝗻 Spring creates the bean instance (using constructor or factory method). 👉 “Object is born” — but not ready yet. 🔹 2. 𝗗𝗲𝗽𝗲𝗻𝗱𝗲𝗻𝗰𝘆 𝗜𝗻𝗷𝗲𝗰𝘁𝗶𝗼𝗻 Spring injects required dependencies (@Autowired, constructor injection, etc.) 👉 Now your bean starts gaining power ⚡ 🔹 3. 𝗔𝘄𝗮𝗿𝗲 𝗜𝗻𝘁𝗲𝗿𝗳𝗮𝗰𝗲𝘀 (Optional but powerful) Spring injects internal context via interfaces like: BeanNameAware ApplicationContextAware 👉 Your bean becomes Spring-aware 🧠 🔹 4. 𝗕𝗲𝗮𝗻 𝗣𝗼𝘀𝘁-𝗣𝗿𝗼𝗰𝗲𝘀𝘀𝗶𝗻𝗴 (Before Init) Custom logic via BeanPostProcessor 👉 Great place for custom proxies, logging, auditing 🔹 5. 𝗜𝗻𝗶𝘁𝗶𝗮𝗹𝗶𝘇𝗮𝘁𝗶𝗼𝗻 𝗣𝗵𝗮𝘀𝗲 This is where your bean becomes fully ready! Ways to initialize: @PostConstruct InitializingBean.afterPropertiesSet() Custom init-method 👉 “I’m ready to serve!” 💪 🔹 6. 𝗕𝗲𝗮𝗻 𝗣𝗼𝘀𝘁-𝗣𝗿𝗼𝗰𝗲𝘀𝘀𝗶𝗻𝗴 (After Init) Another chance to modify the bean (AOP magic happens here ✨) 🔹 7. 𝗕𝗲𝗮𝗻 𝗶𝘀 𝗥𝗲𝗮𝗱𝘆 𝘁𝗼 𝗨𝘀𝗲 Finally, your bean is in action 🎯 🔹 8. 𝗗𝗲𝘀𝘁𝗿𝘂𝗰𝘁𝗶𝗼𝗻 𝗣𝗵𝗮𝘀𝗲 When the app shuts down: @PreDestroy DisposableBean.destroy() Custom destroy-method 👉 Cleanup resources 🧹 #SpringBeansLifecycle #Java #BackendDevelopment #SpringBoot #SoftwareEngineering #SpringBootwithVC
Spring Bean Lifecycle: Understanding Spring Boot Application Initialization
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
-
🚀 Day 17/100: Spring Boot From Zero to Production Topic: Activating Profiles in Spring Boot -> Why Activation Matters Creating profiles isn’t enough You need to activate them to use their config Otherwise, Spring Boot falls back to the default profile. -> Method 1: JVM Argument Pass this when running your app: -Dspring.profiles.active=dev Common for: Local development Switching configs quickly Loads application-dev.yaml -> Method 2: Environment Variable Set: SPRING_PROFILES_ACTIVE=dev Best for: Production environments CI/CD pipelines -> Default Behavior No active profile? default gets loaded Others are ignored Quick Insight Profiles = Config separation Activation = Making them work Simple concept. Powerful impact. This might sound simple but stay consistent. We’re building production mindset step by step. #Java #SpringBoot #SoftwareDevelopment #100DaysOfCode #Backend
To view or add a comment, sign in
-
-
Your API is slow. But your code looks fine. Common Spring Boot issue: N+1 queries. 1 query for parent • N queries for children Suddenly: • More DB calls • Higher latency • Poor performance Fix: • Use JOIN FETCH • Use DTO projections • Monitor queries Spring Boot didn’t slow your app. Your data access did. #SpringBoot #Java #Performance #Backend #SystemDesign #Debugging
To view or add a comment, sign in
-
-
🚀 Spring Configuration — The Backbone of Every Spring Boot App When I first started learning Spring Boot, I thought configuration was just “setup stuff.” Turns out… it’s the brain behind everything 🧠 🔹 What is Spring Configuration? It’s how you tell Spring: ✔️ What objects (beans) to create ✔️ How they connect (Dependency Injection) ✔️ How your app should run 🔹 3 Ways to Configure in Spring Boot 1️⃣ Annotation-Based (Most Common) Use "@Component", "@Service", "@Autowired" 👉 Clean, simple, and widely used 2️⃣ Java-Based Configuration Use "@Configuration" + "@Bean" 👉 Gives you full control when needed 3️⃣ application.properties / application.yml 👉 Configure ports, DB, and custom values 🔹 The Magic Annotation ✨ "@SpringBootApplication" It combines: - "@Configuration" - "@EnableAutoConfiguration" - "@ComponentScan" 👉 That’s why Spring Boot feels so easy! 🔹 Realization 💡 Spring Configuration is not just setup… It’s what makes your app: ✔️ Scalable ✔️ Maintainable ✔️ Production-ready 💬 My Take: If you truly understand configuration, you stop “using Spring” …and start thinking like Spring. #SpringBoot #Java #BackendDevelopment #LearnInPublic #Developers #CodingJourney
To view or add a comment, sign in
-
🔥 Why Your Spring Boot App Returns 404 Even After Successful Startup ⸻ 1. Verify Controller Registration (Not Just Scanning) ➡️ Run with --debug and check auto-configuration logs ➡️ Use /actuator/mappings to confirm if endpoints are actually exposed ⚠️ If your endpoint is NOT listed → it’s not a routing problem, it’s a bean registration issue ⸻ 2. Package Structure (Classic Mistake) Spring Boot only scans downward from the main class package ✔️ Correct: com.app ├── Application.java ├── controller ❌ Wrong: com.app com.controller (won’t be scanned) ➡️ Fix with @ComponentScan if needed ⸻ 3. Annotation Issues (Very Common) ➡️ Missing @RestController or @Controller ➡️ Missing @RequestMapping, @GetMapping, etc. ➡️ Using @Controller without @ResponseBody → returns view instead of JSON → looks like 404 ⸻ 4. Context Path / Port Confusion Check: server.servlet.context-path=/api server.port=8081 Your endpoint becomes http://localhost:8081/api/hello ⚠️ Many devs hit /hello → get 404 → panic 😄 ⸻ 5. Spring Security Blocking Requests ➡️ If Spring Security is enabled: * Unauthenticated requests may not reach controller * Misconfigured rules can return 404 instead of 403 ✔️ Temporarily disable or allow all: http.authorizeHttpRequests().anyRequest().permitAll(); 6. DispatcherServlet Not Mapping Requests ➡️ Check if: spring.mvc.servlet.path Or custom servlet config is changing the routing 7. Static Resource Handler Overriding APIs ➡️ If WebMvcConfigurer is customized, static handlers might override API paths ⸻ 8. Wrong HTTP Method ➡️ Calling GET /users but API is @PostMapping("/users") ➡️ Spring returns 404 (not always 405 depending on config) ⸻ 9. Reverse Proxy / Gateway Issues (Production Case) ➡️ If behind: * Nginx * API Gateway Check if path rewriting is happening: /api/users → /users 10. Build / Deployment Mismatch ➡️ Old JAR running? ➡️ Controller added but not redeployed? ✔️ Always verify: ps -ef | grep java #engineering #development #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
-
-
🧠 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
-
-
Spring vs Spring Boot : The simplest way to understand the difference! Spring Framework = A powerful toolbox. You get all the tools (DI, MVC, Security, etc.), but you have to pick, arrange, and wire everything yourself. Lots of manual configuration. Spring Boot = The ready-to-use assembled kit built on Spring. Smart defaults, auto-configuration, embedded server, and starter dependencies so you can start building real apps in minutes instead of hours. In short: Spring gives you full control. Spring Boot gives you speed + less boilerplate. Quick Analogy (Kitchen Style): Spring → You have all the raw ingredients + separate appliances. You do everything manually. Spring Boot → One smart juicer machine. Just add fruits and press start! Most modern projects (REST APIs, microservices) start directly with Spring Boot - while still using the full power of Spring underneath. Which one are you using right now? Or which part confuses you the most? Drop your thoughts 👇 #SpringBoot #SpringFramework #Java #Backend #JavaDeveloper #InterviewTips
To view or add a comment, sign in
-
-
"How will you handle 10GB file uploads in Spring Boot?" This is one of the most common backend interview questions. Most developers get it wrong because they try to solve it at the framework level. The truth — large file uploads are NOT a framework problem. They're an architecture problem. If you're increasing Tomcat's max-file-size, tweaking multipart settings, or buffering files in your Spring Boot app — you're solving the wrong problem. Why frameworks shouldn't handle large files: → Your Spring Boot app is meant to process requests, not transport gigabytes → 10 concurrent 10GB uploads = 100GB pressure on a single pod → One slow client holds a thread hostage for hours → Network blip = restart from 0% → Doesn't scale across multiple pods The right approach — separate authorization from transport: 1. Client → Backend: "I want to upload a file" 2. Backend → Validates user, returns a pre-signed URL 3. Client → Object Storage (S3, GCS, MinIO, R2): Uploads directly 4. Client → Backend: "Upload complete, here's the file key" 5. Backend → Saves metadata in DB Your backend processed maybe 1KB. The object store handled 10GB. When you're hitting framework limits, it's usually a signal that the framework is the wrong place to solve the problem. Move it to where it belongs. #backend
To view or add a comment, sign in
-
🚀 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
To view or add a comment, sign in
-
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