Spring Bean Lifecycle - Yash-777/MyWorld GitHub Wiki
🌱 Spring Bean Lifecycle (Step-by-Step)
1. Instantiation
2. Populate Properties (@Autowired, @Value)
3. BeanNameAware / BeanFactoryAware / ApplicationContextAware
4. Pre-initialization (BeanPostProcessor#postProcessBeforeInitialization)
5. Initialization (@PostConstruct, afterPropertiesSet())
6. Post-initialization (BeanPostProcessor#postProcessAfterInitialization)
7. Ready to use (ApplicationContext is running)
8. Destruction (@PreDestroy, destroy())
Single Java class that demonstrates all 8 stages of the Spring Bean Lifecycle, complete with logs so you can watch the lifecycle unfold in order during app startup and shutdown.
package com.example.lifecycle;
import jakarta.annotation.PostConstruct;
import jakarta.annotation.PreDestroy;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.*;
import org.springframework.context.*;
import org.springframework.stereotype.Component;
@Slf4j
@Component
public class BeanLifecycleDemo implements
BeanNameAware, BeanFactoryAware, ApplicationContextAware,
InitializingBean, DisposableBean, SmartInitializingSingleton {
{
// Why Not Use Instance Block?
// This runs immediately after constructor call, BEFORE dependencies are injected.
}
public BeanLifecycleDemo() {
log.info("1️⃣ Constructor called — Bean instance created");
}
@Override
public void setBeanName(String name) {
log.info("2️⃣ BeanNameAware — Bean name set: {}", name);
}
@Override
public void setBeanFactory(BeanFactory beanFactory) throws BeansException {
log.info("3️⃣ BeanFactoryAware — BeanFactory injected");
}
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
log.info("4️⃣ ApplicationContextAware — ApplicationContext injected");
}
@PostConstruct
public void postConstruct() {
log.info("5️⃣ @PostConstruct — Bean fully constructed and dependencies injected");
}
@Override
public void afterPropertiesSet() throws Exception {
log.info("6️⃣ InitializingBean — afterPropertiesSet() called");
}
@Override
public void afterSingletonsInstantiated() {
log.info("7️⃣ SmartInitializingSingleton — All singleton beans are now instantiated");
}
@PreDestroy
public void preDestroy() {
log.info("8️⃣ @PreDestroy — Pre-destroy method called before bean is destroyed");
}
@Override
public void destroy() throws Exception {
log.info("8️⃣ DisposableBean — destroy() method called during shutdown");
}
}
🧩 Bean Loading Order in Spring Boot