Bean的生命周期整个过程如下:
1.根据Bean的配置情况,实例化一个Bean。
2.根据Spring上下文对实例化的Bean进行依赖注入,即对Bean的属性进行初始化。
3.如果Bean实现了BeanNameAware接口,将调用它实现的setBeanName(String beanId)方法,此处参数传递的是Spring配置文件中Bean的ID。
4.如果Bean实现了BeanFactoryAware接口,将调用它实现的setBeanFactory()方法,此处参数传递的是当前Spring工厂实例的引用。
5.如果Bean实现了ApplicationContextAware接口,将调用它实现的setApplicationContext(ApplicationContext)方法,此处参数传递的是Spring上下文实例的引用。
6.如果Bean关联了BeanPostProcessor接口,将调用预初始化方法postProcessBeforeInitialization(Object obj, String s)对Bean进行操作。
7.如果Bean实现了InitializingBean接口,将调用afterPropertiesSet()方法。
8.如果Bean在Spring配置文件中配置了init-method属性,将自动调用其配置的初始化方法。
9.如果Bean关联了BeanPostProcessor接口,将调用postProcessAfterInitialization(Object obj, String s)方法,由于是在Bean初始化结束时调用After方法,也可用于内存或缓存技术。
以上工作(1至9)完成以后就可以使用该Bean,由于该Bean的作用域是singleton,所以调用的是同一个Bean实例。
10.当Bean不再需要时,将经过销毁阶段,如果Bean实现了DisposableBean接口,将调用其实现的destroy方法将Spring中的Bean销毁。
11.如果在配置文件中通过destroy-method属性指定了Bean的销毁方法,将调用其配置的销毁方法进行销毁。
package life;
public class BeanLife {
public void initMyself(){
System.out.println(this.getClass().getName() + "执行自定义的初始化方法");
}
public void destroyMyself(){
System.out.println(this.getClass().getName() + "执行自定义的销毁方法");
}
}
<!-- 配置bean,使用init-method属性指定初始化方法,使用 destroy-method属性指定销毁方法-->
<bean class="life.BeanLife" id="beanLife" destroy-method="destroyMyself"
init-method="initMyself" />
package test;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import life.BeanLife;
public class TestLife {
public static void main(String[] args) {
// 初始化Spring容器,加载配置文件
// 为了方便演示销毁方法的执行,这里使用ClassPathXmlApplicationContext实现类声明容器
ClassPathXmlApplicationContext xfc = new ClassPathXmlApplicationContext("applicationContext.xml");
System.out.println("获得对象前");
BeanLife blife = (BeanLife) xfc.getBean("beanLife");
System.out.println("获得对象后" + blife);
xfc.close();// 关闭容器,销毁Bean对象
}
}
life.BeanLife执行自定义的初始化方法
获得对象前
获得对象后life.BeanLife@20322d26
三月 25, 2021 6:21:34 下午
org.springframework.context.support.AbstractApplicationContext doClose
信息: Closing org.springframework.context.support.ClassPathXmlApplicationContext@b81eda8: startup date [Thu Mar 25 18:21:34 CST 2021]; root of context hierarchy
life.BeanLife执行自定义的销毁方法