Spring Bean的生命周期

1.Bean 的实例化
public class AbstractAutowireCapableBeanFactory{
    protected Object doCreateBean(**){
        ..
        if (instanceWrapper == null) {
            instanceWrapper = this.createBeanInstance(beanName, mbd, args);
        }
        ..
    }
}

2.Bean 的属性注入(DI)
public class AbstractAutowireCapableBeanFactory{
    protected Object doCreateBean(**){
        ..
        populateBean(beanName, mbd, instanceWrapper);
        ..
    }
}
3.初始化
public class AbstractAutowireCapableBeanFactory{
    protected Object doCreateBean(**){
        ..
        exposedObject = initializeBean(beanName, exposedObject, mbd);
        ..
    }
}

里面分了几步

private void invokeAwareMethods(String beanName, Object bean) {
        if (bean instanceof Aware) {
            if (bean instanceof BeanNameAware) {
                ((BeanNameAware) bean).setBeanName(beanName);
            }
            if (bean instanceof BeanClassLoaderAware) {
                ClassLoader bcl = getBeanClassLoader();
                if (bcl != null) {
                    ((BeanClassLoaderAware) bean).setBeanClassLoader(bcl);
                }
            }
            if (bean instanceof BeanFactoryAware) {
                ((BeanFactoryAware) bean).setBeanFactory(AbstractAutowireCapableBeanFactory.this);
            }
        }
    }

if (mbd == null || !mbd.isSynthetic()) {
      //---------------------------Bean生命周期一部分,调用postProcessAfterInitialization-----------------------
      wrappedBean = applyBeanPostProcessorsAfterInitialization(wrappedBean, beanName);
   }
 1. 实现了BeanNameAware接口的话,Spring将Bean的Id传递给setBeanName()方法
 2. 实现了BeanClassLoaderAware接口的话,Spring将getBeanClassLoader传给Bean
 3. 如果Bean实现了BeanFactoryAware接口的话,Spring将调用setBeanFactory()方法,将BeanFactory容器实例传入
 4. 如果Bean 实现了BeanPostProcessor接口,Spring就将调用他们的postProcessAfterInitialization()方法。 

此时,Bean已经准备就绪,他们将一直驻留在应用上下文中,直到应用上下文被销毁。但是如果bean实现了DisposableBean接口,pring将调用它的destory()接口方法,同样,如果bean使用了destory-method 声明销毁方法,该方法也会被调用。

5.销毁

你可能感兴趣的:(Spring Bean的生命周期)