Bean在Spring容器中的生命周期

配置在Spring中的Bean在Spring容器中从加载到销毁会经历那些过程呢?如果实现一些特定的Spring接口,这些特定接口的方法会在什么时候被调用呢?本文简单介绍一下这些过程.

Bean在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 的下载地址:请点这里

相关阅读

相关推荐