【Spring源码解析】Bean生命周期

Bean创建过程

  1. 实例化bean 设置bean属性
  2. Aware(注入Bean ID、BeanFactory和AppCtx)
  3. BeanPostProcessor(s).postProcessBeforeInitialization
  4. InitializingBean(s).afterPropertiesSet
  5. 定制的Bean init方法
  6. BeanPostProcessor(s).postProcessAfterInitialization
  7. Bean初始化完毕

Bean销毁过程

  1. 若实现了DisposableBean接口,则会调用destory方法
  2. 若配置了destory-method属性,则会调用其配置的销毁方法

各种接口方法分类

  1. Bean自身的方法
    • Bean本身调用的方法
    • 通过配置文件中的init-method和destroy-method指定的方法
  2. Bean级生命周期接口方法
    • BeanNameAware
    • BeanFactoryAware
    • InitializingBean
    • DiposableBean
  3. 容器级生命周期接口方法
    • BeanPostProcessor 后置处理器,作用是在Bean对象在实例化和依赖注入完毕后,在显示调用初始化方法的前后添加我们自己的逻辑。注意是Bean实例化完毕后及依赖注入完成后触发的.
    • InstantiationAwareBeanPostProcessor
  4. 工厂后处理器接口方法(容器级,在应用上下文装配配置文件之后立即调用)
    • AspectJWeavingEnabler
    • ConfigurationClassPostProcessor
    • CustomAutowireConfigure

测试Demo

  • LifeCycleBean
package com.example.spring.bean;

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.*;
import org.springframework.beans.factory.config.BeanPostProcessor;

public class LifeCycleBean implements BeanPostProcessor, BeanNameAware,
        BeanClassLoaderAware, BeanFactoryAware, InitializingBean, DisposableBean {

    private String name;

    public LifeCycleBean() {
        System.out.println("-----------------------1.Bean构造器");
    }
    public void setName(String name) {
        System.out.println("-----------------------2.Bean属性注入");
        this.name = name;
    }
    @Override
    public void setBeanName(String name) {
        System.out.println("-----------------------3.BeanNameAware的setBeanName()");
    }

    @Override
    public void setBeanClassLoader(ClassLoader classLoader) {
        System.out.println("-----------------------4.BeanClassLoaderAware的setBeanClassLoader()");
    }

    @Override
    public void setBeanFactory(BeanFactory beanFactory) throws BeansException {
        System.out.println("-----------------------5.BeanFactoryAware的setBeanFactory()");
    }



    @Override
    public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
        System.out.println("-----------------------6.[初始化之前]BeanPostProcessor的postProcessBeforeInitialization()");
        return bean;
    }
    @Override
    public void afterPropertiesSet() throws Exception {
        System.out.println("-----------------------7.[初始化中,属性注入后]InitializingBean的afterPropertiesSet()");
    }
    public void initMethod() {
        System.out.println("-----------------------8.调用<bean>的init-method属性自定义的初始化方法");
    }
    @Override
    public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
        System.out.println("-----------------------9.[初始化之后]BeanPostProcessor的postProcessAfterInitialization()");
        return bean;
    }

    public void normalMethod() {
        System.out.println("-----------------------10.[容器初始化完成]程序运行,当JVM关闭时,销毁容器");
    }

    @Override
    public void destroy() throws Exception {
        System.out.println("-----------------------11.[容器销毁]DisposableBean的destroy()");
    }

    public void destroyMethod() {
        System.out.println("-----------------------12.[容器销毁]调用<bean>的destory-method属性自定义的销毁方法");
    }

    public String getName() {
        return name;
    }
}
  • spring-bean-life-cycle.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="lifeCycleBean" class="com.example.spring.bean.LifeCycleBean" destroy-method="destroyMethod" init-method="initMethod">
        <property name="name" value="name"/>
    </bean>

</beans>
  • Test
public class SpringTest {
    /**
     * 测试Bean生命周期
     * */
    @Test
    public void testBeanLifeCycle() {
        ClassPathResource resource = new ClassPathResource("spring-bean-life-cycle.xml");
        DefaultListableBeanFactory factory = new DefaultListableBeanFactory();
        factory.addBeanPostProcessor(new LifeCycleBean());
        XmlBeanDefinitionReader reader = new XmlBeanDefinitionReader(factory);
        reader.loadBeanDefinitions(resource);

        LifeCycleBean lifeCycleBean = (LifeCycleBean) factory.getBean("lifeCycleBean");
        lifeCycleBean.normalMethod();

        factory.destroySingleton("lifeCycleBean");
    }
}

源码解析

AbstractAutowireCapableBeanFactory的createBean()方法

   protected Object createBean(String beanName, RootBeanDefinition mbd, Object[] args) throws BeanCreationException {
        if (this.logger.isDebugEnabled()) {
            this.logger.debug("Creating instance of bean '" + beanName + "'");
        }

        RootBeanDefinition mbdToUse = mbd;
        //确定加载Bean 的 class
        Class<?> resolvedClass = this.resolveBeanClass(mbd, beanName, new Class[0]);
        if (resolvedClass != null && !mbd.hasBeanClass() && mbd.getBeanClassName() != null) {
            mbdToUse = new RootBeanDefinition(mbd);
            mbdToUse.setBeanClass(resolvedClass);
        }
      //验证以及准备需要覆盖的方法
        try {
            mbdToUse.prepareMethodOverrides();
        } catch (BeanDefinitionValidationException var7) {
            throw new BeanDefinitionStoreException(mbdToUse.getResourceDescription(), beanName, "Validation of method overrides failed", var7);
        }

        Object beanInstance;
        try {
            beanInstance = this.resolveBeforeInstantiation(beanName, mbdToUse);
            if (beanInstance != null) {
                return beanInstance;
            }
        } catch (Throwable var8) {
            throw new BeanCreationException(mbdToUse.getResourceDescription(), beanName, "BeanPostProcessor before instantiation of bean failed", var8);
        }
      //创建Bean
        beanInstance = this.doCreateBean(beanName, mbdToUse, args);
        if (this.logger.isDebugEnabled()) {
            this.logger.debug("Finished creating instance of bean '" + beanName + "'");
        }

        return beanInstance;
    }

AbstractAutowireCapableBeanFactory的doCreateBean()方法

protected Object doCreateBean(final String beanName, final RootBeanDefinition mbd, Object[] args) throws BeanCreationException {
        BeanWrapper instanceWrapper = null;
        if (mbd.isSingleton()) {
            instanceWrapper = (BeanWrapper)this.factoryBeanInstanceCache.remove(beanName);
        }

        if (instanceWrapper == null) {
          //创建bean实例
            instanceWrapper = this.createBeanInstance(beanName, mbd, args);
        }

        final Object bean = instanceWrapper != null ? instanceWrapper.getWrappedInstance() : null;
        Class<?> beanType = instanceWrapper != null ? instanceWrapper.getWrappedClass() : null;
        mbd.resolvedTargetType = beanType;
        synchronized(mbd.postProcessingLock) {
            if (!mbd.postProcessed) {
                try {
                    this.applyMergedBeanDefinitionPostProcessors(mbd, beanType, beanName);
                } catch (Throwable var17) {
                    throw new BeanCreationException(mbd.getResourceDescription(), beanName, "Post-processing of merged bean definition failed", var17);
                }

                mbd.postProcessed = true;
            }
        }
        //针对循环依赖:单例、允许循环依赖、该bean属性尚未装配(二级缓存 Map earlySingletonObjects)
        boolean earlySingletonExposure = mbd.isSingleton() && this.allowCircularReferences && this.isSingletonCurrentlyInCreation(beanName);
        if (earlySingletonExposure) {
            if (this.logger.isDebugEnabled()) {
                this.logger.debug("Eagerly caching bean '" + beanName + "' to allow for resolving potential circular references");
            }
          //为避免循环依赖, 在bean 初始化完成前,就将创建 bean 实例的
          //ObjectFactory 放入 工厂缓存(三级缓存 singletonFactories)
            this.addSingletonFactory(beanName, new ObjectFactory<Object>() {
                public Object getObject() throws BeansException {
                    return AbstractAutowireCapableBeanFactory.this.getEarlyBeanReference(beanName, mbd, bean);
                }
            });
        }

        Object exposedObject = bean;

        try {
           //对 bean 属性进行填充
            this.populateBean(beanName, mbd, instanceWrapper);
            if (exposedObject != null) {
              //调用初始化方法 如init-method、注入Aware 对象
                exposedObject = this.initializeBean(beanName, exposedObject, mbd);
            }
        } catch (Throwable var18) {
            if (var18 instanceof BeanCreationException && beanName.equals(((BeanCreationException)var18).getBeanName())) {
                throw (BeanCreationException)var18;
            }

            throw new BeanCreationException(mbd.getResourceDescription(), beanName, "Initialization of bean failed", var18);
        }

        if (earlySingletonExposure) {
            Object earlySingletonReference = this.getSingleton(beanName, false);
            if (earlySingletonReference != null) {
                if (exposedObject == bean) {
                    exposedObject = earlySingletonReference;
                } else if (!this.allowRawInjectionDespiteWrapping && this.hasDependentBean(beanName)) {
                    String[] dependentBeans = this.getDependentBeans(beanName);
                    Set<String> actualDependentBeans = new LinkedHashSet(dependentBeans.length);
                    String[] var12 = dependentBeans;
                    int var13 = dependentBeans.length;

                    for(int var14 = 0; var14 < var13; ++var14) {
                        String dependentBean = var12[var14];
                        if (!this.removeSingletonIfCreatedForTypeCheckOnly(dependentBean)) {
                            actualDependentBeans.add(dependentBean);
                        }
                    }

                    if (!actualDependentBeans.isEmpty()) {
                        throw new BeanCurrentlyInCreationException(beanName, "Bean with name '" + beanName + "' has been injected into other beans [" + StringUtils.collectionToCommaDelimitedString(actualDependentBeans) + "] in its raw version as part of a circular reference, but has eventually been wrapped. This means that said other beans do not use the final version of the bean. This is often the result of over-eager type matching - consider using 'getBeanNamesForType' with the 'allowEagerInit' flag turned off, for example.");
                    }
                }
            }
        }

        try {
          //注册DisposableBean 以便在销毁时调用
            this.registerDisposableBeanIfNecessary(beanName, bean, mbd);
            return exposedObject;
        } catch (BeanDefinitionValidationException var16) {
            throw new BeanCreationException(mbd.getResourceDescription(), beanName, "Invalid destruction signature", var16);
        }
    }

AbstractAutowireCapableBeanFactory的initializeBean()方法

protected Object initializeBean(final String beanName, final Object bean, RootBeanDefinition mbd) {
        if (System.getSecurityManager() != null) {
            AccessController.doPrivileged(new PrivilegedAction<Object>() {
                public Object run() {
                    AbstractAutowireCapableBeanFactory.this.invokeAwareMethods(beanName, bean);
                    return null;
                }
            }, this.getAccessControlContext());
        } else {
            //检查当前Bean对象是否实现相关Aware接口
            //BeanNameAware、BeanClassLoaderAware、BeanFactoryAware
            this.invokeAwareMethods(beanName, bean);
        }
      
        Object wrappedBean = bean;
        if (mbd == null || !mbd.isSynthetic()) {
          //BeanPostProcessor增强处理 前置处理
            wrappedBean = this.applyBeanPostProcessorsBeforeInitialization(bean, beanName);
        }

        try {
          //当前 bean 是否实现 InitializingBean 如果实现要调用afterPropertiesSet()
          //判断是否指定了 init-method(),利用反射机制执行指定初始化方法
            this.invokeInitMethods(beanName, wrappedBean, mbd);
        } catch (Throwable var6) {
            throw new BeanCreationException(mbd != null ? mbd.getResourceDescription() : null, beanName, "Invocation of init method failed", var6);
        }

        if (mbd == null || !mbd.isSynthetic()) {
          //BeanPostProcessor增强处理 后置处理
            wrappedBean = this.applyBeanPostProcessorsAfterInitialization(wrappedBean, beanName);
        }

        return wrappedBean;
    }
posted @ 2020-09-24 15:56  zendwang  阅读(203)  评论(0编辑  收藏  举报