Demystifying Spring Bean Lifecycle: From Creation to Destruction
This article explains the Spring Bean lifecycle in depth, covering IoC fundamentals, each lifecycle stage, extension points such as Aware interfaces and BeanPostProcessor, and provides a step‑by‑step code walkthrough that maps the execution flow from bean creation to destruction.
1. Basics
1.1 What is IoC?
IoC (Inversion of Control) means delegating object creation to the container, so the container controls the objects instead of the objects creating their own dependencies.
It follows the Hollywood principle – "Don’t call us, we’ll call you" – where the IoC container injects required dependencies.
Key questions: who controls whom, what is controlled, and why it is an inversion.
Who controls whom? The IoC container controls the beans.
What is controlled? External resources such as files and other beans.
Why is it an inversion? Because the container, not the bean, obtains and injects dependencies.
The dependency acquisition is inverted.
1.2 Bean Lifecycle
For prototype beans, after getBean the container stops managing the instance; the lifecycle discussion focuses on singleton beans.
Lifecycle steps:
Instantiation : create bean instance.
Property Assignment : set bean properties and dependencies.
Initialization : multiple steps – pre‑initialization (steps 3‑4), actual initialization (steps 5‑6), post‑initialization (step 7).
Destruction : register destroy callbacks (step 8) and finally execute destroy logic (steps 9‑10).
1.3 Execution Flow
Example bean LouzaiBean implements several Spring lifecycle interfaces.
public class LouzaiBean implements InitializingBean, BeanFactoryAware, BeanNameAware, DisposableBean {
private String name;
public LouzaiBean() { System.out.println("1.调用构造方法:我出生了!"); }
public void setName(String name) { this.name = name; System.out.println("2.设置属性:我的名字叫"+name); }
@Override public void setBeanName(String s) { System.out.println("3.调用BeanNameAware#setBeanName方法:我要上学了,起了个学名"); }
@Override public void setBeanFactory(BeanFactory beanFactory) throws BeansException { System.out.println("4.调用BeanFactoryAware#setBeanFactory方法:选好学校了"); }
@Override public void afterPropertiesSet() throws Exception { System.out.println("6.InitializingBean#afterPropertiesSet方法:入学登记"); }
public void init() { System.out.println("7.自定义init方法:努力上学ing"); }
@Override public void destroy() throws Exception { System.out.println("9.DisposableBean#destroy方法:平淡的一生落幕了"); }
public void destroyMethod() { System.out.println("10.自定义destroy方法:睡了,别想叫醒我"); }
public void work() { System.out.println("Bean使用中:工作,只有对社会没有用的人才放假。。"); }
}A custom MyBeanPostProcessor demonstrates pre‑ and post‑initialization hooks.
public class MyBeanPostProcessor implements BeanPostProcessor {
@Override public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
System.out.println("5.BeanPostProcessor.postProcessBeforeInitialization方法:到学校报名啦");
return bean;
}
@Override public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
System.out.println("8.BeanPostProcessor#postProcessAfterInitialization方法:终于毕业,拿到毕业证啦!");
return bean;
}
}Configuration (partial applicationContext.xml) registers the bean and the post‑processor.
<bean name="myBeanPostProcessor" class="demo.MyBeanPostProcessor"/>
<bean name="louzaiBean" class="demo.LouzaiBean" init-method="init" destroy-method="destroyMethod">
<property name="name" value="楼仔"/>
</bean>Test entry point loads the context, retrieves louzaiBean, invokes work(), and then closes the context.
public class MyTest {
public static void main(String[] args) {
ApplicationContext context = new ClassPathXmlApplicationContext("classpath:applicationContext.xml");
LouzaiBean louzaiBean = (LouzaiBean) context.getBean("louzaiBean");
louzaiBean.work();
((ClassPathXmlApplicationContext) context).destroy();
}
}Running the test prints the full lifecycle trace, matching the diagram.
1.4 Extension Points
The lifecycle includes four extension categories:
Aware interfaces (e.g., BeanNameAware.setBeanName(), BeanFactoryAware.setBeanFactory()).
BeanPostProcessor methods ( postProcessBeforeInitialization, postProcessAfterInitialization).
Lifecycle interfaces ( InitializingBean.afterPropertiesSet(), DisposableBean.destroy()).
Configured init/destroy methods via XML ( init(), destroyMethod()).
2. Source Code Walkthrough
Note: The code was tested with Spring 5.2.15.RELEASE; other versions may differ.
The walkthrough follows the actual Spring source:
2.1 Entry Point
Starting from doGetBean(), the container fails to find a singleton and proceeds to create the bean.
2.2 Instantiation
doCreateBean()calls createBeanInstance(), which invokes instantiateBean() to construct LouzaiBean.
2.3 Property Assignment
populateBean()triggers applyPropertyValues(), ultimately calling the bean’s setter to assign the name property.
2.4 Initialization
The container runs initializeBean(), which:
Invokes Aware methods ( setBeanName, setBeanFactory).
Executes BeanPostProcessor pre‑initialization.
Calls InitializingBean.afterPropertiesSet() and the custom init() method.
Runs BeanPostProcessor post‑initialization.
2.5 Destruction
When the context is closed, destroy() is invoked, first executing DisposableBean.destroy() and then the configured destroyMethod().
3. Final Recap
Key methods to remember:
doCreateBean() : entry point for bean creation.
createBeanInstance() : instantiate the bean.
populateBean() : perform dependency injection.
initializeBean() : handle Aware callbacks, BeanPostProcessor hooks, initialization interfaces, and custom init methods.
destroy() : execute DisposableBean and custom destroy methods.
The populateBean() step is where dependency injection occurs, a frequent interview topic (including circular dependencies).
Reference
Spring Bean lifecycle article: https://juejin.cn/post/7075168883744718856
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
Su San Talks Tech
Su San, former staff at several leading tech companies, is a top creator on Juejin and a premium creator on CSDN, and runs the free coding practice site www.susan.net.cn.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
