Spring框架:第三章:對象的生命周期及單例bean生命周期的11個步驟
IOC之Bean的生命周期
實(shí)驗(yàn)22:創(chuàng)建帶有生命周期方法的bean
public class Person {
private Integer id;
private String name;
public void init() {
System.out.println("這是person對象的初始化方法");
}
public void destroy() {
System.out.println("這是person對象的銷毀方法");
}
配置信息:
<!--
init-method="init" 初始化方法 在對象被創(chuàng)建之后
destroy-method="destroy" 銷毀方法 在容器關(guān)閉的時候執(zhí)行
-->
<bean id="p24" class="com.pojo.Person" init-method="init" destroy-method="destroy">
<property name="id" value="24"></property>
</bean>
測試代碼:
@Test
public void test13() throws Exception {
ClassPathXmlApplicationContext applicationContext = new ClassPathXmlApplicationContext("applicationContext.xml");
System.out.println(applicationContext.getBean("p24"));
applicationContext.close();
}
Bean的后置處理器BeanPostProcessor
bean的后置處理器,可以在bean對象初始化之前或之后做一些工作。
要使用bean的后置處理器,需要實(shí)現(xiàn)這個接口并配置。
實(shí)驗(yàn)23:測試bean的后置處理器
person對象,一定要有初始化方法
public class Person {
private Integer id;
private String name;
private Car car;
public void init() {
System.out.println("這是person對象的初始化方法");
}
后置處理器對象
public class MyBeanPostProcessor implements BeanPostProcessor {
@Override
public Object postProcessAfterInitialization(Object bean, String id) throws BeansException {
System.out.println("初始化之后執(zhí)行 bean => " + bean + ", id => " + id);
return bean;
}
/**
* bean是當(dāng)前正在初始化的對象
* id 是當(dāng)前正在初始化對象的id值
*/
@Override
public Object postProcessBeforeInitialization(Object bean, String id) throws BeansException {
System.out.println("初始化之前執(zhí)行 bean => " + bean + ", id => " + id);
return bean;
}
}
配置信息:
<!--
init-method="init" 初始化方法 在對象被創(chuàng)建之后
destroy-method="destroy" 銷毀方法 在容器關(guān)閉的時候執(zhí)行
-->
<bean id="p24" class="com.pojo.Person" init-method="init" destroy-method="destroy">
<property name="id" value="24"></property>
</bean>
<!-- 配置bean的后置處理器 -->
<bean class="com.pojo.MyBeanPostProcessor" />
測試的代碼:
@Test
public void test13() throws Exception {
ClassPathXmlApplicationContext applicationContext = new ClassPathXmlApplicationContext("bean2.xml");
System.out.println(applicationContext.getBean("p24"));
applicationContext.close();
}
對于單例的bean,生命周期有11個步驟:
1.instantiate bean對象實(shí)例化,bean對象實(shí)例化,是在加載配置文件的時候?qū)嵗摹<?,我們啟動spring容器的時候,加載配置文件,此時就實(shí)例化bean了。
2.populate properties 封裝屬性
3.如果Bean實(shí)現(xiàn)BeanNameAware, 執(zhí)行 setBeanName
4.如果Bean實(shí)現(xiàn)BeanFactoryAware 或者 ApplicationContextAware,設(shè)置工廠 setBeanFactory 或者上下文對象 setApplicationContext
5.如果存在類實(shí)現(xiàn) BeanPostProcessor(后處理Bean) ,執(zhí)行postProcessBeforeInitialization(此點(diǎn)常常用來增強(qiáng)bean)
6.如果Bean實(shí)現(xiàn)InitializingBean 執(zhí)行 afterPropertiesSet
7.調(diào)用 指定初始化方法 init
8.如果存在類實(shí)現(xiàn) BeanPostProcessor(后處理Bean) ,執(zhí)行postProcessAfterInitialization(此點(diǎn)常常用來增強(qiáng)bean)
9.執(zhí)行業(yè)務(wù)處理
10.如果Bean實(shí)現(xiàn) DisposableBean 執(zhí)行 destroy
11.調(diào)用 指定銷毀方法