Spring源码之Spring后置处理器详解

Cricket 2020-06-07

什么是Spring的后置处理器?

  Spring的后置处理器贯穿了整个springBean的实例化前后。

Spring后置处理器都有哪些类,哪些方法?

  一.InstantiationAwareBeanPostProcessor

  InstantiationAwareBeanPostProcessor接口继承BeanPostProcessor接口,它内部提供了3个方法,再加上BeanPostProcessor接口内部的2个方法,所以实现这个接口需要实现5个方法。InstantiationAwareBeanPostProcessor接口的主要作用在于目标对象的实例化过程中需要处理的事情,包括实例化对象的前后过程以及实例的属性设置在org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory#createBean()方法的Object bean = resolveBeforeInstantiation(beanName, mbdToUse);方法里面执行了这个后置处理器。

  1、postProcessBeforeInstantiation

  在目标对象实例化之前调用,方法的返回值类型是Object,我们可以返回任何类型的值。由于这个时候目标对象还未实例化,所以这个返回值可以用来代替原本该生成的目标对象的实例(一般都是代理对象)。如果该方法的返回值代替原本该生成的目标对象,后续只有postProcessAfterInitialization方法会调用,其它方法不再调用;否则按照正常的流程走。

  2、postProcessAfterInstantiation

  方法在目标对象实例化之后调用,这个时候对象已经被实例化,但是该实例的属性还未被设置,都是null。如果该方法返回false,会忽略属性值的设置;如果返回true,会按照正常流程设置。

  3、postProcessPropertyValues

  方法对属性值进行修改(这个时候属性值还未被设置,但是我们可以修改原本该设置进去的属性值)。如果postProcessAfterInstantiation方法返回false,该方法不会被调用。可以在该方法内对属性值进行修改。

  4、postProcessBeforeInitialization&postProcessAfterInitialization

  父接口BeanPostProcessor的2个方法postProcessBeforeInitialization和postProcessAfterInitialization都是在目标对象被实例化之后,并且属性也被设置之后调用的。

  二、SmartInstantiationAwareBeanPostProcessor

  智能实例化Bean后置处理器(继承InstantiationAwareBeanPostProcessor)

  1、determineCandidateConstructors

  检测Bean的构造器,可以检测出多个候选构造器。

  2、getEarlyBeanReference

  循环引用的后置处理器,这个东西比较复杂, 获得提前暴露的bean引用。主要用于解决循环引用的问题,只有单例对象才会调用此方法。

  3、predictBeanType

  预测bean的类型。

  三、MergedBeanDefinitionPostProcessor

  1、postProcessMergedBeanDefinition

  缓存bean的注入信息的后置处理器,仅仅是缓存或者干脆叫做查找更加合适,没有完成注入,注入是另外一个后置处理器的作用。

Spring后置处理器源码展现:

  第一次执行后置处理器:

  代码路径:org/springframework/beans/factory/support/AbstractAutowireCapableBeanFactory.java

      AbstractAutowireCapableBeanFactory.createBean()--resolveBeforeInstantiation() ---这里是springbean的生命周期开始的地方

                              -applyBeanPostProcessorsBeforeInstantiation()

                              --applyBeanPostProcessorsAfterInitialization()

protected Object resolveBeforeInstantiation(String beanName, RootBeanDefinition mbd) {
        Object bean = null;
        if (!Boolean.FALSE.equals(mbd.beforeInstantiationResolved)) {
            // Make sure bean class is actually resolved at this point.
            if (!mbd.isSynthetic() && hasInstantiationAwareBeanPostProcessors()) {
                Class<?> targetType = determineTargetType(beanName, mbd);
                if (targetType != null) {
                    // 第一个后置处理器执行
                    bean = applyBeanPostProcessorsBeforeInstantiation(targetType, beanName);
                    if (bean != null) {
                        bean = applyBeanPostProcessorsAfterInitialization(bean, beanName);
                    }
                }
            }
            mbd.beforeInstantiationResolved = (bean != null);
        }
        return bean;
    }
applyBeanPostProcessorsBeforeInstantiation():
protected Object applyBeanPostProcessorsBeforeInstantiation(Class<?> beanClass, String beanName) {
        //getBeanPostProcessors:拿到容器中所有实现了BeanPostProcessors接口的类
        for (BeanPostProcessor bp : getBeanPostProcessors()) {
            if (bp instanceof InstantiationAwareBeanPostProcessor) {
                //第一个后置处理器
                InstantiationAwareBeanPostProcessor ibp = (InstantiationAwareBeanPostProcessor) bp;
                Object result = ibp.postProcessBeforeInstantiation(beanClass, beanName);
                if (result != null) {
                    return result;
                }
            }
        }
        return null;
    }

InstantiationAwareBeanPostProcessor.postProcessBeforeInstantiation();

  第二次执行后置处理器:

    代码路径:org/springframework/beans/factory/support/AbstractAutowireCapableBeanFactory.java

         AbstractAutowireCapableBeanFactory.createBeanInstance()--Constructor<?>[] ctors = determineConstructorsFromBeanPostProcessors(beanClass, beanName);---第二次执行后置处理器使用的地方
    SmartInstantiationAwareBeanPostProcessor.determineCandidateConstructors()

protected Constructor<?>[] determineConstructorsFromBeanPostProcessors(@Nullable Class<?> beanClass, String beanName)
            throws BeansException {

        if (beanClass != null && hasInstantiationAwareBeanPostProcessors()) {
            for (BeanPostProcessor bp : getBeanPostProcessors()) {
                if (bp instanceof SmartInstantiationAwareBeanPostProcessor) {
                    SmartInstantiationAwareBeanPostProcessor ibp = (SmartInstantiationAwareBeanPostProcessor) bp;
                    Constructor<?>[] ctors = ibp.determineCandidateConstructors(beanClass, beanName);
                    if (ctors != null) {
                        return ctors;
                    }
                }
            }
        }
        return null;
    }

SmartInstantiationAwareBeanPostProcessor.determineCandidateConstructors()

第三次执行后置处理器:

  代码路径:org/springframework/beans/factory/support/AbstractAutowireCapableBeanFactory.java

  AbstractAutowireCapableBeanFactory.applyMergedBeanDefinitionPostProcessors()---第三次执行后置处理器

protected void applyMergedBeanDefinitionPostProcessors(RootBeanDefinition mbd, Class<?> beanType, String beanName) {
        for (BeanPostProcessor bp : getBeanPostProcessors()) {
            if (bp instanceof MergedBeanDefinitionPostProcessor) {
                MergedBeanDefinitionPostProcessor bdp = (MergedBeanDefinitionPostProcessor) bp;
                bdp.postProcessMergedBeanDefinition(mbd, beanType, beanName);
            }
        }
    }

  org/springframework/beans/factory/annotation/AutowiredAnnotationBeanPostProcessor.java

public void postProcessMergedBeanDefinition(RootBeanDefinition beanDefinition, Class<?> beanType, String beanName) {
        InjectionMetadata metadata = findAutowiringMetadata(beanName, beanType, null);
        metadata.checkConfigMembers(beanDefinition);
    }

第四次执行后置处理器:

  代码路径:org/springframework/beans/factory/support/AbstractAutowireCapableBeanFactory.java

        AbstractAutowireCapableBeanFactory.getEarlyBeanReference()---第四次执行后置处理器

protected Object getEarlyBeanReference(String beanName, RootBeanDefinition mbd, Object bean) {
        Object exposedObject = bean;
        if (!mbd.isSynthetic() && hasInstantiationAwareBeanPostProcessors()) {
            for (BeanPostProcessor bp : getBeanPostProcessors()) {
                if (bp instanceof SmartInstantiationAwareBeanPostProcessor) {
                    SmartInstantiationAwareBeanPostProcessor ibp = (SmartInstantiationAwareBeanPostProcessor) bp;
                    exposedObject = ibp.getEarlyBeanReference(exposedObject, beanName);
                }
            }
        }
        return exposedObject;
    }

  SmartInstantiationAwareBeanPostProcessor.getEarlyBeanReference()//解决循环依赖的

@Override
    public Object getEarlyBeanReference(Object bean, String beanName) throws BeansException {
        return bean;
    }

第五次执行后置处理器:

  代码路径:

org/springframework/beans/factory/support/AbstractAutowireCapableBeanFactory.java
AbstractAutowireCapableBeanFactory.populateBean()--InstantiationAwareBeanPostProcessor.postProcessAfterInstantiation()---第五次执行后置处理器

protected void populateBean(String beanName, RootBeanDefinition mbd, @Nullable BeanWrapper bw) {
        if (bw == null) {
            if (mbd.hasPropertyValues()) {
                throw new BeanCreationException(
                        mbd.getResourceDescription(), beanName, "Cannot apply property values to null instance");
            }
            else {
                // Skip property population phase for null instance.
                return;
            }
        }

        // Give any InstantiationAwareBeanPostProcessors the opportunity to modify the
        // state of the bean before properties are set. This can be used, for example,
        // to support styles of field injection.
        boolean continueWithPropertyPopulation = true;
        // ***第五次执行后置处理器***
        if (!mbd.isSynthetic() && hasInstantiationAwareBeanPostProcessors()) {
            for (BeanPostProcessor bp : getBeanPostProcessors()) {
                if (bp instanceof InstantiationAwareBeanPostProcessor) {
                    InstantiationAwareBeanPostProcessor ibp = (InstantiationAwareBeanPostProcessor) bp;
                    if (!ibp.postProcessAfterInstantiation(bw.getWrappedInstance(), beanName)) {
                        continueWithPropertyPopulation = false;
                        break;
                    }
                }
            }
        }

        if (!continueWithPropertyPopulation) {
            return;
        }

        PropertyValues pvs = (mbd.hasPropertyValues() ? mbd.getPropertyValues() : null);

        if (mbd.getResolvedAutowireMode() == AUTOWIRE_BY_NAME || mbd.getResolvedAutowireMode() == AUTOWIRE_BY_TYPE) {
            MutablePropertyValues newPvs = new MutablePropertyValues(pvs);
            // Add property values based on autowire by name if applicable.
            if (mbd.getResolvedAutowireMode() == AUTOWIRE_BY_NAME) {
                autowireByName(beanName, mbd, bw, newPvs);
            }
            // Add property values based on autowire by type if applicable.
            if (mbd.getResolvedAutowireMode() == AUTOWIRE_BY_TYPE) {
                autowireByType(beanName, mbd, bw, newPvs);
            }
            pvs = newPvs;
        }

        boolean hasInstAwareBpps = hasInstantiationAwareBeanPostProcessors();
        boolean needsDepCheck = (mbd.getDependencyCheck() != AbstractBeanDefinition.DEPENDENCY_CHECK_NONE);

        PropertyDescriptor[] filteredPds = null;
        if (hasInstAwareBpps) {
            if (pvs == null) {
                pvs = mbd.getPropertyValues();
            }
            for (BeanPostProcessor bp : getBeanPostProcessors()) {
                if (bp instanceof InstantiationAwareBeanPostProcessor) {
                    InstantiationAwareBeanPostProcessor ibp = (InstantiationAwareBeanPostProcessor) bp;
                    //
                    PropertyValues pvsToUse = ibp.postProcessProperties(pvs, bw.getWrappedInstance(), beanName);
                    if (pvsToUse == null) {
                        if (filteredPds == null) {
                            filteredPds = filterPropertyDescriptorsForDependencyCheck(bw, mbd.allowCaching);
                        }
                        // ***第六次执行后置处理器***
                        pvsToUse = ibp.postProcessPropertyValues(pvs, filteredPds, bw.getWrappedInstance(), beanName);
                        if (pvsToUse == null) {
                            return;
                        }
                    }
                    pvs = pvsToUse;
                }
            }
        }
        if (needsDepCheck) {
            if (filteredPds == null) {
                filteredPds = filterPropertyDescriptorsForDependencyCheck(bw, mbd.allowCaching);
            }
            checkDependencies(beanName, mbd, filteredPds, pvs);
        }

        if (pvs != null) {
            applyPropertyValues(beanName, mbd, bw, pvs);
        }
    }
InstantiationAwareBeanPostProcessor.postProcessAfterInstantiation();
@Override
    public boolean postProcessAfterInstantiation(Object bean, String beanName) throws BeansException {
        return true;
    }

第六次执行后置处理器:

  代码路径:org/springframework/beans/factory/support/AbstractAutowireCapableBeanFactory.java

    AbstractAutowireCapableBeanFactory.populateBean()--InstantiationAwareBeanPostProcessor.postProcessPropertyValues()---第六次执行后置处理器

populateBean()//同上面第五次调用后置处理器

  InstantiationAwareBeanPostProcessor.postProcessPropertyValues();

public PropertyValues postProcessPropertyValues(
            PropertyValues pvs, PropertyDescriptor[] pds, Object bean, String beanName) {

        return postProcessProperties(pvs, bean, beanName);
    }

第七次执行后置处理器:

  代码路径:org/springframework/beans/factory/support/AbstractAutowireCapableBeanFactory.java

    AbstractAutowireCapableBeanFactory.initializeBean()--applyBeanPostProcessorsBeforeInitialization()--BeanPostProcessor.postProcessBeforeInitialization()---第七次执行后置处理器

protected Object initializeBean(final String beanName, final Object bean, @Nullable RootBeanDefinition mbd) {
        if (System.getSecurityManager() != null) {
            AccessController.doPrivileged((PrivilegedAction<Object>) () -> {
                invokeAwareMethods(beanName, bean);
                return null;
            }, getAccessControlContext());
        }
        else {
            invokeAwareMethods(beanName, bean);
        }

        Object wrappedBean = bean;
        if (mbd == null || !mbd.isSynthetic()) {
            //***第七次调用后置处理器***
            wrappedBean = applyBeanPostProcessorsBeforeInitialization(wrappedBean, beanName);
        }

        try {
            invokeInitMethods(beanName, wrappedBean, mbd);
        }
        catch (Throwable ex) {
            throw new BeanCreationException(
                    (mbd != null ? mbd.getResourceDescription() : null),
                    beanName, "Invocation of init method failed", ex);
        }
        if (mbd == null || !mbd.isSynthetic()) {
            //***第八次调用后置处理器***
            wrappedBean = applyBeanPostProcessorsAfterInitialization(wrappedBean, beanName);
        }

        return wrappedBean;
    }
public Object applyBeanPostProcessorsBeforeInitialization(Object existingBean, String beanName)
            throws BeansException {

        Object result = existingBean;
        for (BeanPostProcessor processor : getBeanPostProcessors()) {
            Object current = processor.postProcessBeforeInitialization(result, beanName);
            if (current == null) {
                return result;
            }
            result = current;
        }
        return result;
    }

第八次执行后置处理器:

  代码路径:org/springframework/beans/factory/support/AbstractAutowireCapableBeanFactory.java

      AbstractAutowireCapableBeanFactory.initializeBean()--applyBeanPostProcessorsAfterInitialization()--BeanPostProcessor.postProcessAfterInitialization()---第八次执行后置处理器

public Object applyBeanPostProcessorsAfterInitialization(Object existingBean, String beanName)
            throws BeansException {

        Object result = existingBean;
        for (BeanPostProcessor processor : getBeanPostProcessors()) {
            Object current = processor.postProcessAfterInitialization(result, beanName);
            if (current == null) {
                return result;
            }
            result = current;
        }
        return result;
    }

第九次执行后置处理器:

  bean销毁的时候执行的后置处理器。

Spring执行BeanPostProcessor的时间和作用:

  当一个bean实例化的过程中,首先会初始化bean的构造方法,然后执行BeanPostProcessor.postProcessBeforeInitialization()方法,然后执行添加@PostConstruct注解的方法,然后执行BeanPostProcessor.postProcessAfterInitialization()的方法。(spring-aop的实行原理)

Spring源码之Spring后置处理器详解

相关推荐

TiDBPingCAP / 0评论 2020-07-29