Most developers use Spring Beans daily. Very few understand what actually happens inside the container. Here’s the Spring Bean lifecycle — technically simplified: 🔁 Container Startup 1️⃣ Instantiation Bean object is created (via reflection). 2️⃣ Dependency Injection @Autowired / constructor injection resolves dependencies. 3️⃣ Aware Interfaces (optional) BeanNameAware, ApplicationContextAware, etc. 4️⃣ BeanPostProcessor (Before Init) postProcessBeforeInitialization() runs. 5️⃣ Initialization Phase @PostConstruct InitializingBean.afterPropertiesSet() Custom init-method 6️⃣ BeanPostProcessor (After Init) postProcessAfterInitialization() runs. 👉 This is where Spring may wrap your bean with a proxy. That’s how @Transactional, @Async, @Cacheable, and AOP work. The injected object is often a proxy — not your original class. 7️⃣ Bean Ready for Use 🔻 Shutdown Phase 8️⃣ Destruction @PreDestroy DisposableBean.destroy() (Default applies to singletons.) Why this matters: • @Transactional fails in self-invocation • Proxy-based behavior confuses debugging • Prototype inside Singleton behaves unexpectedly • Circular dependency issues during early creation Once you understand the lifecycle, Spring stops feeling like magic. It becomes predictable. #SpringBoot #SpringFramework #Java #BackendEngineering #AOP #Microservices
Spring Bean Lifecycle: Understanding Instantiation to Destruction
More Relevant Posts
-
Many of us think Spring works using annotations. It doesn’t. Spring works using proxies. Annotations are just triggers. The real behavior comes from what Spring wraps around your code. Whenever you use: ✅ @Transactional ✅ @Async ✅ @Cacheable ✅ @Retryable ✅ Spring AOP You are not calling your original method directly. You are calling a proxy object. That proxy decides what should happen before and after your method runs. Example with @Transactional: 1️⃣ Proxy intercepts method call 2️⃣ Transaction starts 3️⃣ Your method executes 4️⃣ Commit / rollback happens Your class never handled the transaction. The proxy did. This also explains many confusing Spring behaviors: ❌ @Transactional not working in self-invocation ❌ Different behavior in tests vs production ❌ Private methods not intercepted ❌ Final methods causing issues ❌ Unexpected performance overhead Most “Spring bugs” are actually proxy misunderstandings. The Real Insight If something behaves differently than expected in Spring, ask: 👉 Am I calling the proxy or the actual object? Once you understand proxies, Spring stops feeling magical. It becomes predictable. And predictable systems are easier to debug. #SpringBoot #Java #BackendEngineering #SpringFramework #AOP #SoftwareArchitecture #Microservices
To view or add a comment, sign in
-
-
✅ What is a Spring Bean? A Spring Bean is an object that is created, managed, and maintained by the Spring IoC Container. In simple terms: Any class whose object is managed by Spring is called a Spring Bean. 🔄 How Spring Bean Works 1️⃣ You define a class 2️⃣ You mark it with an annotation like @Component 3️⃣ Spring creates the object 4️⃣ Spring manages its lifecycle 📌 Example: @Component class Engine { } ✔ Spring creates the Engine object ✔ Spring manages it ✔ This object is called a Spring Bean 🧠 Why Spring Beans are Important No manual object creation (new) Loose coupling Easy dependency injection Better maintainability 💡 Simple Line to Remember Spring Bean = Object managed by Spring Container #Spring #SpringBoot #SpringBean #Java #LearningInPublic #BackendDevelopment
To view or add a comment, sign in
-
-
How I Detect Bean Initialization Issues in Spring Boot When facing bean initialization issues in large applications, I follow these steps: ✔️ Check startup logs carefully ✔️ Look for exceptions like BeanCreationException or dependency errors From here we will clearly show which bean is failed and why. ✔️ Identify the exact bean from the stack trace ✔️ Check for circular dependencies If two beans depends on each other in that scenario spring throws an error. ✔️ Verify active profiles I will check is there any missing or wrong profiles configured. ✔️ Ensure proper component scanning and base package structure I will make sure all classes are inside base package of main class annotated with @SpringBootApplication. Most of the time, reading logs properly helps find the root cause quickly. #SpringBoot #Java #BackendDevelopment #Debugging
To view or add a comment, sign in
-
🌱 Bean Creation in Spring — More Important Than It Looks In Spring Boot, we use beans everywhere — but many developers don’t fully think about how they are created and managed. A Spring Bean is simply an object managed by the IoC (Inversion of Control) container. 🔹 Beans can be created using: • @Component, @Service, @Repository • @Configuration + @Bean • Auto-configuration 🔹 Why Bean management matters: • Dependency Injection reduces tight coupling • Singleton scope improves performance (default scope) • Lifecycle management (@PostConstruct, @PreDestroy) ensures controlled initialization Good backend systems are not just about writing classes — they’re about letting the container manage object creation efficiently. Understanding bean lifecycle = better Spring architecture. #Java #SpringBoot #SpringFramework #DependencyInjection #BackendEngineering
To view or add a comment, sign in
-
📌 Spring Boot Annotation Series – Part 8 ✅ @Component annotation The @Component annotation is used to mark a class as a Spring-managed bean 👇 🔹 Why do we use @Component? To tell Spring: 👉 “Create an object of this class and manage it.” - To enable dependency injection - To let Spring detect the class during component scanning 🔹 How does it work? When Spring Boot starts: - It scans packages (using @ComponentScan) - Finds classes annotated with @Component - Creates and registers them as beans in the Spring container 🔹 Simple example @Component public class EmailService { public void sendEmail() { System.out.println("Email sent"); } } Now this class can be injected using: @Autowired private EmailService emailService; 🔹 In simple words @Component tells Spring to automatically create and manage this class as a bean. 👉 🧠 Quick Understanding - Marks a class as a Spring bean - Detected during component scanning - Enables dependency injection #SpringBoot #Java #Component #BackendDevelopment #LearningInPublic
To view or add a comment, sign in
-
Every Spring Boot application revolves around Beans. But do you really know what happens behind the scenes? Here’s the complete lifecycle of a Spring Bean inside the IoC Container: 1️⃣ Container Started 2️⃣ Bean Created 3️⃣ Dependencies Injected (@Autowired, Constructor, Setter) 4️⃣ Bean Initialized (@PostConstruct, init methods, InitializingBean) 5️⃣ Bean Ready for Use 6️⃣ Bean Used by the Application 7️⃣ Container Shutdown 8️⃣ Bean Destroyed (@PreDestroy, destroy(), DisposableBean) 💡 Why This Matters Understanding the bean lifecycle helps you: ✔ Debug initialization issues ✔ Handle resource management properly ✔ Avoid memory leaks ✔ Use @PostConstruct and @PreDestroy correctly ✔ Perform better in Spring interviews Most developers use Spring. Fewer understand what happens inside the container. Master the internals → Write better backend systems. #Spring #SpringBoot #Java #BackendDevelopment #JavaDeveloper #Microservices #SoftwareEngineering #Programming #Coding #DeveloperCommunity #TechLearning #SpringFramework #InterviewPreparation #CodingInterview #FullStackDeveloper
To view or add a comment, sign in
-
-
🔹 Spring Concept: Bean Lifecycle In the Spring Framework, every object managed by the Spring IoC container is called a Bean. Understanding the Bean Lifecycle helps developers control how objects are created, initialized, and destroyed. 📌 Stages of Spring Bean Lifecycle 1️⃣ Instantiation Spring creates the bean instance. 2️⃣ Dependency Injection Spring injects required dependencies. 3️⃣ Initialization Custom initialization logic runs using: • @PostConstruct • InitializingBean • custom init-method 4️⃣ Bean Ready for Use The bean is now fully initialized and used in the application. 5️⃣ Destruction When the application context closes, cleanup logic runs using: • @PreDestroy • DisposableBean • custom destroy-method 💡 Example: @Component public class NotificationService { @PostConstruct public void init() { System.out.println(“Bean Initialized”); } @PreDestroy public void destroy() { System.out.println(“Bean Destroyed”); } } ✨ Understanding the Bean lifecycle helps developers manage resources efficiently and write better Spring applications. #Java #SpringBoot #SpringFramework #BackendDevelopment #SoftwareEngineering
To view or add a comment, sign in
-
Hi everyone 👋 📌 Spring Boot Annotation Series Part 21 – @PathVariable @PathVariable is used to extract values from the URL path and bind them to method parameters. It is part of the Spring Framework and widely used in REST APIs built with Spring Boot. 🔹 Why Do We Use @PathVariable? In REST APIs, resources are identified using IDs in the URL. Example: GET /users/101 Here, 101 is part of the URL path. @PathVariable helps us capture that value inside the controller method. 🔹 Basic Example @RestController @RequestMapping("/users") public class UserController { @GetMapping("/{id}") public String getUserById(@PathVariable Long id) { return "User ID is: " + id; } } 👉 If request is: GET http://localhost:8080/users/101 Output: User ID is: 101 🔹 In Simple Words @PathVariable takes dynamic values from the URL and passes them to the controller method. #SpringBoot #Java #RESTAPI #PathVariable #BackendDevelopment #InterviewPreparation
To view or add a comment, sign in
-
🧠 Spring @Transactional – Why Your Rollback Didn’t Happen This is one of the most dangerous “it works… until it doesn’t” scenarios in Spring. You mark a method with @Transactional. You throw an exception. You expect a rollback. But nothing rolls back. And you don’t notice… until production. ❌ The Problem: Self-Invocation In Spring, @Transactional works through proxies. When a method inside the same class calls another @Transactional method using this.method(), 👉 it bypasses the proxy. 👉 no interception happens. 👉 no transactional behavior is applied. In the image above: updateUser() calls this.sendEmail() That internal call never goes through Spring’s proxy. If sendEmail() fails? The save operation may NOT roll back. Silent failure. No warning. ✅ The Fix: Go Through the Proxy Instead of calling the method directly: Use self-injection Or move the transactional logic to a separate service When you call through the injected proxy (self.sendEmail()), Spring can properly intercept the call and apply transactional behavior. Now your rollback works as expected. 🎯 The Real Lesson Transactions are not just annotations. They are proxy-driven runtime behavior. If you don’t understand how Spring AOP works under the hood, you’ll eventually debug this at 2 AM. Have you ever been bitten by self-invocation in Spring? Let’s hear your story 👇 #Java #SpringBoot #SpringFramework #Transactional #SoftwareArchitecture #CleanCode #JavaDevelopment #BackendDevelopment
To view or add a comment, sign in
-
-
🚀 What Exactly Is a Bean in Spring? (Simple but Important) Sometimes the simplest questions are the ones we forget to explain clearly. As Spring developers, we often say: “Bean is just an object managed by Spring IoC.” But what does that really mean? In the Spring Framework: A Bean is an object that is: ✔ Created by the Spring IoC container ✔ Managed by the container ✔ Injected using Dependency Injection (DI) ✔ Stored inside the ApplicationContext ✔ Controlled through its lifecycle If you create an object using new, it’s just a normal object. If Spring creates and manages it — it becomes a Bean. Example: @Service public class PaymentService { } Because of @Service, Spring registers this class as a Bean and manages it inside the container. 💡 Why this matters? Understanding Beans properly helps in: Debugging injection issues Avoiding NoUniqueBeanDefinitionException Managing lifecycle correctly Writing clean architecture Sometimes we use Spring daily but forget the fundamentals behind it. Still learning. Still refining basics. #SpringBoot #Java #BackendDevelopment #CleanCode #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