Spring ApplicationContext & Bean Lifecycle Explained

Day 02 – Bean Lifecycle & ApplicationContext ================================================ Yesterday I started with Spring Core fundamentals. Today I went deeper into something that actually makes Spring powerful Bean Lifecycle and ApplicationContext. Most developers use Spring. But not everyone understands what happens internally when the application starts. ================================================ What is ApplicationContext? ApplicationContext is the Spring container. When we run a Spring Boot application: SpringApplication.run(Application.class, args); Spring creates an ApplicationContext. From that moment, Spring starts: • Creating objects (Beans) • Injecting dependencies • Managing lifecycle • Handling configurations • Managing resources It becomes the brain of the application. ============================================= What is a Bean Lifecycle? A Spring Bean goes through multiple stages from creation to destruction. Here is what actually happens: 1. Spring creates the object (Constructor runs) 2. Dependencies are injected 3. Initialization logic executes 4. Bean is ready to use 5. When application shuts down → destroy logic runs Practical Example @Component public class StudentService {   public StudentService() {     System.out.println("Constructor called");   }   @PostConstruct   public void init() {     System.out.println("Bean initialized");   }   @PreDestroy   public void cleanup() {     System.out.println("Bean destroyed");   } } What happens here? * Constructor → Object creation * @PostConstruct → Runs after dependency injection * @PreDestroy → Runs before application shutdown This is the full lifecycle. ============================================= Spring is not just annotations. It is a container that controls object creation, initialization, and destruction. Understanding Bean Lifecycle makes you think like a backend engineer not just someone who writes APIs. Tomorrow: Bean Scopes (Singleton vs Prototype vs Request vs Session) * #Java #SpringBoot #SpringFramework #BackendDevelopment #Microservices #LearningInPublic

To view or add a comment, sign in

Explore content categories