SpringBean的生命周期

时间:2022-01-02 14:44:47
Bean生命周期
1. 调⽤用默认构造⽅方法创建Bean实例例 2. 执⾏行行Bean的属性依赖注⼊入。 3. BeanNameAware的setBeanName()
 如果实现了了BeanNameAware接⼝ 4. BeanFactoryAware的setBeanFactory()
 如果实现了了BeanFactoryAware接⼝ 5. BeanPostProcessor的 processBeforeInitialization() 6. InitializingBean的afterPropertiesSet() 7. Bean定义⽂文件中定义init-method 8. BeanPostProcessors的 processAfterInitialization() 9. DisposableBean的destroy() 10.Bean定义⽂文件中定义destroy-method
SpringBean的生命周期

我这边定义一个LifecycleBean类实现了BeanNameAware, BeanPostProcessor, BeanFactoryAware, InitializingBean, DisposableBean接口,还包括了init,destroy,和自定义的destroy-method
package firstMaven;

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.BeanFactoryAware;
import org.springframework.beans.factory.BeanNameAware;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.beans.factory.support.DefaultListableBeanFactory;

public class LifecycleBean
implements BeanNameAware, BeanPostProcessor, BeanFactoryAware, InitializingBean, DisposableBean {

public void init(){
System.out.println("init()");
}
public void destroy(){

System.out.println("destroy()");
}

public void afterPropertiesSet() throws Exception {
System.out.println("afterPropertiesSet()");

}

public void setBeanFactory(BeanFactory beanFactory) throws BeansException {
((DefaultListableBeanFactory)beanFactory).addBeanPostProcessor(this);
System.out.println("setBeanFactory");

}

public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
System.out.println("postProcessAfterInitialization");
return bean;
}

public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
System.out.println("postProcessBeforeInitialization");
return bean;
}

public void setBeanName(String arg0) {
System.out.println("setBeanName");

}
public void destroy1(){
System.out.println("close()");
}

}



定义了一个beanlifecycle.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:p="http://www.springframework.org/schema/p"
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 ="helloChina" class = "firstMaven.LifecycleBean"
init-method ="init" destroy-method="destroy1">
</bean>

</beans>


注意这边的 destroy-method,上面的类中也就用这个定义的方法了。通常这边是close的,是用来松耦合的 最后我创了一个加载类看他运行顺序: SpringBean的生命周期
最终结果: setBeanNamesetBeanFactorypostProcessBeforeInitializationafterPropertiesSet()init()postProcessAfterInitializationget beandoClosedestroy()close()