1:写在前面
本文只涉及流程图和具体实例,不涉及源码级别分析,对源码感兴趣的朋友可以移步这里。
2:流程图
3:实例
3.1:代码
public class MyLifeCycleBean implements BeanNameAware,
BeanFactoryAware,
BeanClassLoaderAware,
BeanPostProcessor,
InitializingBean,
DisposableBean {
private String test;
// 普通方法
public void display(){
System.out.println("普通类实例方法调用...");
}
public String getTest() {
return test;
}
public void setTest(String test) {
this.test = test;
}
@Override
public void setBeanClassLoader(ClassLoader classLoader) {
System.out.println("BeanClassLoaderAware 被调用了。。。");
}
@Override
public void setBeanFactory(BeanFactory beanFactory) throws BeansException {
System.out.println("BeanFactoryAware 被调用了。。。");
}
@Override
public void setBeanName(String name) {
System.out.println("BeanNameAware 被调用了。。。");
}
@Override
public void destroy() throws Exception {
System.out.println("DisposableBean#destroy被调用了。。。");
}
@Override
public void afterPropertiesSet() throws Exception {
System.out.println("InitializingBean#afterPropertiesSet被调用了。。。");
}
@Override
public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
System.out.println("BeanPostProcessor#postProcessBeforeInitialization被调用了。。。");
return bean;
}
@Override
public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
System.out.println("BeanPostProcessor#postProcessAfterInitialization被调用了。。。");
return bean;
}
public void initMethod(){
System.out.println("init-method 被调用...");
}
public void destroyMethdo(){
System.out.println("destroy-method 被调用...");
}
}
3.2:xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd">
<bean id="lifeCycle" class="yudaosourcecode.studyhelp.MyLifeCycleBean"
init-method="initMethod" destroy-method="destroyMethdo">
<property name="test" value="test"/>
</bean>
</beans>
3.3:测试
@Test
public void mylifecyclebeantest() {
ClassPathResource resource
= new ClassPathResource("mylifecyclebeantest.xml");
XmlBeanFactory xbf = new XmlBeanFactory(resource);
// 手动添加后置bean处理器
xbf.addBeanPostProcessor(new MyLifeCycleBean());
MyLifeCycleBean lifeCycle
= xbf.getBean("lifeCycle", MyLifeCycleBean.class);
lifeCycle.display();
// 销毁容器
xbf.destroySingletons();
}
运行:
BeanNameAware 被调用了。。。
BeanClassLoaderAware 被调用了。。。
BeanFactoryAware 被调用了。。。
BeanPostProcessor#postProcessBeforeInitialization被调用了。。。
InitializingBean#afterPropertiesSet被调用了。。。
init-method 被调用...
BeanPostProcessor#postProcessAfterInitialization被调用了。。。
普通类实例方法调用...
DisposableBean#destroy被调用了。。。
destroy-method 被调用...
Process finished with exit code 0