配置在Spring中的Bean在Spring容器中從加載到銷毀會經歷那些過程呢?如果實現一些特定的Spring接口,這些特定接口的方法會在什麼時候被調用呢?本文簡單介紹一下這些過程.
Bean在Spring容器中的生命周期如下圖所示:
1,調用Bean的構造函數(或者工廠方法)實例化Bean.
2,對Bean的成員變量賦值.
3,如果Bean實現了BeanNameAware,調用Bean的setBeanName方法.
4,如果Bean實現了BeanFactoryAware,調用Bean的setBeanFactory方法.
5,如果Bean實現了ApplicationContextAware,調用Bean的setApplicationContext方法.
6,如果容器中配置了BeanPostProcessor,調用BeanPostProcessor的postProcessBeforeInitialization方法(如果有多個BeanPostProcessor,調用每一個BeanPostProcessor的postProcessBeforeInitialization方法).
6,如果Bean實現了InitializingBean,調用Bean的afterPropertiesSet方法.
7,如果Bean配置了init-method方法,調用init-method配置的Bean方法.
8,如果容器中配置了BeanPostProcessor,調用BeanPostProcessor的postProcessAfterInitialization方法.(如果有多個BeanPostProcessor,調用每一個BeanPostProcessor的postProcessAfterInitialization方法).
9,Bean處於可以使用的狀態.
10,Spring容器關閉.
11,4,如果Bean實現了DisposableBean,調用Bean的destroy方法.
12,如果Bean配置了destroy-method方法,調用destroy-method配置的Bean的方法.
實例:LifeCycleBean implements InitializingBean, DisposableBean,BeanNameAware,BeanFactoryAware, ApplicationContextAware,配置了init-method="init" destroy-method="cleanup",容器中有兩個BeanPostProcessor
public class LifeCycleBean implements InitializingBean, DisposableBean,
BeanNameAware,BeanFactoryAware, ApplicationContextAware {
private String str = "default";
public LifeCycleBean() {
System.out.println("construct LifecycleBean ***************");
}
public LifeCycleBean(String str) {
this.str = str;
}
public String getStr() {
return str;
}
public void setStr(String str) {
System.out.println("setStr ***************");
this.str = str;
}
public void init() {
System.out.println("init mtd ***************");
}
public void cleanup() {
System.out.println("cleanup mtd ***************");
}
public void afterPropertiesSet() throws Exception {
System.out.println("afterPropertiesSet ***************");
}
public void destroy() throws Exception {
System.out.println("destroy ***************");
}
public void setApplicationContext(ApplicationContext arg0)
throws BeansException {
System.out.println("setApplicationContext***************");
}
public void setBeanFactory(BeanFactory arg0) throws BeansException {
System.out.println("setBeanFactory***************");
}
public void setBeanName(String arg0) {
System.out.println("setBeanName***************" + arg0);
}
}
public class MyBeanPostProcessor implements BeanPostProcessor {
public Object postProcessBeforeInitialization(Object bean, String beanName)
throws BeansException {
System.out.println("************** MyBeanPostProcessor postProcessBeforeInitialization Bean '" + beanName);
return bean;
}
public Object postProcessAfterInitialization(Object bean, String beanName)
throws BeansException {
System.out.println("************** MyBeanPostProcessor postProcessAfterInitialization Bean '" + beanName);
return bean;
}
}
Spring 的詳細介紹:請點這裡
Spring 的下載地址:請點這裡