Spring配置
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">
<bean class="com.test.spring.beanfactoryCtx.MyBeanPostProcessor" />
<bean class="com.test.spring.beanfactoryCtx.MyBeanPostProcessor1" />
<bean name="lifeCycleBean" class="com.test.spring.beanfactoryCtx.LifeCycleBean" init-method="init" destroy-method="cleanup">
<property name="str" value="test str"/>
</bean>
</beans>
调用代码:注意在从main方法启动Spring的话,需要registerShutdownHook才能看到destroy方法和由destroy-method配置的方法的调用.
ApplicationContext ctx = new ClassPathXmlApplicationContext("classpath:conf/bfactoryCtx1.xml");
((ClassPathXmlApplicationContext)ctx).registerShutdownHook();
LifeCycleBean bean1 = ctx.getBean("lifeCycleBean",LifeCycleBean.class);
System.out.println("***********" + bean1 + " " + bean1.getStr());
输出结果如下:
construct LifecycleBean ***************
setStr *************** #1
setBeanName***************lifeCycleBean
setBeanFactory***************
setApplicationContext***************
************** MyBeanPostProcessor postProcessBeforeInitialization Bean 'lifeCycleBean #2
************** MyBeanPostProcessor1 postProcessBeforeInitialization Bean 'lifeCycleBean #2
afterPropertiesSet ***************
init mtd ***************
************** MyBeanPostProcessor postProcessAfterInitialization Bean 'lifeCycleBean #2
************** MyBeanPostProcessor1 postProcessAfterInitialization Bean 'lifeCycleBean #2
***********com.test.spring.beanfactoryCtx.LifeCycleBean@157fb52 test4 #3
destroy ***************
cleanup mtd ***************
#1为成员变量赋值的步骤
#2如果有多个BeanPostProcessor的话,每一个BeanPostProcessor都会被调用一次.
#3Bean 被客户端代码使用
