registerBeanPostProcessors

106 阅读34分钟

registerBeanPostProcessors

下面开始介绍refresh()方法中的registerBeanPostProcessors()方法,该方法是对bean的全局创建的处理器。

  1. 对于spring而言想要对一个bean执行额外的回调动作,我们可以通过各种不同的Aware接口,或者是beanPostProcessor接口来实现。
  2. 但是这些实现类,或者说实现子类的统一接口是:BeanPostProcessor。
  3. 然而对于bean的后置回调处理的功能spring在处理的时候其实已经是有一套顺序或者规则来定义执行,下面我们通过一张简图来理解一下:

  1. 在refresh()方法中的finishBeanFactoryInitialization(beanFactory);方法的最后一个方法:beanFactory.preInstantiateSingletons();中
@Override
public void preInstantiateSingletons() throws BeansException {
    if (logger.isTraceEnabled()) {
        logger.trace("Pre-instantiating singletons in " + this);
    }
    // Iterate over a copy to allow for init methods which in turn register new bean definitions.
    // While this may not be part of the regular factory bootstrap, it does otherwise work fine.
    // 遍历副本以允许 init 方法,这些方法反过来注册新的 Bean 定义。虽然这可能不是常规工厂引导程序的一部分,但它在其他方面确实工作正常。
    List<String> beanNames = new ArrayList<>(this.beanDefinitionNames);
    // Trigger initialization of all non-lazy singleton beans... 触发所有非惰性单例 bean 的初始化...
    for (String beanName : beanNames) {
        /**
         * 1.当你自己实现的BeanFactoryPostProcessor接口后冻结了之后再去修改BeanDefinition的属性,
         * 2.所以这里获取的BeanDefinition不是最新的,代表你修改的BeanDefinition不会生效
         */
        RootBeanDefinition bd = getMergedLocalBeanDefinition(beanName);
        if (!bd.isAbstract() && bd.isSingleton() && !bd.isLazyInit()) {
            if (isFactoryBean(beanName)) {
                Object bean = getBean(FACTORY_BEAN_PREFIX + beanName);
                if (bean instanceof FactoryBean) {
                    FactoryBean<?> factory = (FactoryBean<?>) bean;
                    boolean isEagerInit;
                    if (System.getSecurityManager() != null && factory instanceof SmartFactoryBean) {
                        isEagerInit = AccessController.doPrivileged(
                                (PrivilegedAction<Boolean>) ((SmartFactoryBean<?>) factory)::isEagerInit,
                                getAccessControlContext()
                        );
                    } else {
                        isEagerInit = (factory instanceof SmartFactoryBean && ((SmartFactoryBean<?>) factory).isEagerInit());
                    }
                    if (isEagerInit) {
                        getBean(beanName);
                    }
                }
            } else {
                getBean(beanName);
            }
        }
    }
    // Trigger post-initialization callback for all applicable beans... 触发所有适用 bean 的初始化后回调...
    for (String beanName : beanNames) {
        Object singletonInstance = getSingleton(beanName);
        if (singletonInstance instanceof SmartInitializingSingleton) {
            SmartInitializingSingleton smartSingleton = (SmartInitializingSingleton) singletonInstance;
            if (System.getSecurityManager() != null) {
                AccessController.doPrivileged(
                        (PrivilegedAction<Object>) () -> {
                            smartSingleton.afterSingletonsInstantiated();
                            return null;
                        },
                        getAccessControlContext()
                );
            } else {
                smartSingleton.afterSingletonsInstantiated();
            }
        }
    }
}
  1. 上述的两个getBean()方法,进入任意一个都行:
@Override
public Object getBean(String name) throws BeansException {
    return doGetBean(name, null, null, false);
}
  1. 进入doGetBean方法:
protected <T> T doGetBean(String name, @Nullable Class<T> requiredType, @Nullable Object[] args, boolean typeCheckOnly) throws BeansException {
    //校验当前的bean的名称是否规范,比如*^%@乱七八糟的字符
    String beanName = transformedBeanName(name);
    Object bean;
    // Eagerly check singleton cache for manually registered singletons. 去单例池中寻找被spring实例化好的bean对象
    Object sharedInstance = getSingleton(beanName);
    // 判断当前被创建的bean实例是否存在,一般情况下来说,是没有的,所以会进入到else中
    if (sharedInstance != null && args == null) {
        if (logger.isTraceEnabled()) {
            if (isSingletonCurrentlyInCreation(beanName)) {
                logger.trace("Returning eagerly cached instance of singleton bean '" + beanName + "' that is not fully initialized yet - a consequence of a circular reference");
            } else {
                logger.trace("Returning cached instance of singleton bean '" + beanName + "'");
            }
        }
        bean = getObjectForBeanInstance(sharedInstance, name, beanName, null);
    } else {
        // Fail if we're already creating this bean instance: We're assumably within a circular reference.
        if (isPrototypeCurrentlyInCreation(beanName)) {
            throw new BeanCurrentlyInCreationException(beanName);
        }
        // Check if bean definition exists in this factory.
        BeanFactory parentBeanFactory = getParentBeanFactory();
        if (parentBeanFactory != null && !containsBeanDefinition(beanName)) {
            // Not found -> check parent.
            String nameToLookup = originalBeanName(name);
            if (parentBeanFactory instanceof AbstractBeanFactory) {
                return ((AbstractBeanFactory) parentBeanFactory).doGetBean(nameToLookup, requiredType, args, typeCheckOnly);
            } else if (args != null) {
                // Delegation to parent with explicit args.
                return (T) parentBeanFactory.getBean(nameToLookup, args);
            } else if (requiredType != null) {
                // No args -> delegate to standard getBean method.
                return parentBeanFactory.getBean(nameToLookup, requiredType);
            } else {
                return (T) parentBeanFactory.getBean(nameToLookup);
            }
        }
        //到这一步其实对于当前要被实例化的bean的beanDefinition的定义大致完成,可以开始实例化了
        if (!typeCheckOnly) {
            /**
             * 作用:
             * 1.该方法就是将当前的bean放入到alreadyCreated这个set集合中开始实例化
             * 2.直接清除了mergeBeanDefinitionMap表示下面要开始获取的bd都是要最新的Bean实例
             */
            markBeanAsCreated(beanName);
        }
        try {
            RootBeanDefinition mbd = getMergedLocalBeanDefinition(beanName);
            checkMergedBeanDefinition(mbd, beanName, args);
            // Guarantee initialization of beans that the current bean depends on.由于自动注入的存在,所以在这里要确保当前 Bean 所依赖的 bean 的初始化
            String[] dependsOn = mbd.getDependsOn();
            if (dependsOn != null) {
                for (String dep : dependsOn) {
                    if (isDependent(beanName, dep)) {
                        throw new BeanCreationException(mbd.getResourceDescription(), beanName, "Circular depends-on relationship between '" + beanName + "' and '" + dep + "'");
                    }
                    registerDependentBean(dep, beanName);
                    try {
                        getBean(dep);
                    } catch (NoSuchBeanDefinitionException ex) {
                        throw new BeanCreationException(mbd.getResourceDescription(), beanName, "'" + beanName + "' depends on missing bean '" + dep + "'", ex);
                    }
                }
            }
            // Create bean instance. 在这里开始bean的实例化
            if (mbd.isSingleton()) {
                //getSingleton:除了调用createBean创建了Beans
                sharedInstance = getSingleton(beanName, () -> {
                    try {
                        // 创建Bean
                        return createBean(beanName, mbd, args);
                    } catch (BeansException ex) {
                        // Explicitly remove instance from singleton cache: It might have been put there
                        // eagerly by the creation process, to allow for circular reference resolution.
                        // Also remove any beans that received a temporary reference to the bean.
                        destroySingleton(beanName);
                        throw ex;
                    }
                });
                bean = getObjectForBeanInstance(sharedInstance, name, beanName, mbd);
                //注意这里不是原型Bean创建的流程,只是一个较为特殊的创建流程(当BeanFactoryPostProcessor方法中调用了冻结方法后再设置Prototype属性)
            } else if (mbd.isPrototype()) {
                // It's a prototype -> create a new instance. 这是一个原型 - >创建一个新实例。
                Object prototypeInstance = null;
                try {
                    beforePrototypeCreation(beanName);
                    //创建bean
                    prototypeInstance = createBean(beanName, mbd, args);
                } finally {
                    afterPrototypeCreation(beanName);
                }
                bean = getObjectForBeanInstance(prototypeInstance, name, beanName, mbd);
            } else {
                String scopeName = mbd.getScope();
                if (!StringUtils.hasLength(scopeName)) {
                    throw new IllegalStateException("No scope name defined for bean '" + beanName + "'");
                }
                Scope scope = this.scopes.get(scopeName);
                if (scope == null) {
                    throw new IllegalStateException("No Scope registered for scope name '" + scopeName + "'");
                }
                try {
                    Object scopedInstance = scope.get(beanName, () -> {
                        beforePrototypeCreation(beanName);
                        try {
                            return createBean(beanName, mbd, args);
                        } finally {
                            afterPrototypeCreation(beanName);
                        }
                    });
                    bean = getObjectForBeanInstance(scopedInstance, name, beanName, mbd);
                } catch (IllegalStateException ex) {
                    throw new BeanCreationException(beanName,
                            "Scope '" + scopeName + "' is not active for the current thread; consider " +
                                    "defining a scoped proxy for this bean if you intend to refer to it from a singleton",
                            ex);
                }
            }
        } catch (BeansException ex) {
            cleanupAfterBeanCreationFailure(beanName);
            throw ex;
        }
    }
    // Check if required type matches the type of the actual bean instance.
    if (requiredType != null && !requiredType.isInstance(bean)) {
        try {
            T convertedBean = getTypeConverter().convertIfNecessary(bean, requiredType);
            if (convertedBean == null) {
                throw new BeanNotOfRequiredTypeException(name, requiredType, bean.getClass());
            }
            return convertedBean;
        } catch (TypeMismatchException ex) {
            if (logger.isTraceEnabled()) {
                logger.trace("Failed to convert bean '" + name + "' to required type '" + ClassUtils.getQualifiedName(requiredType) + "'", ex);
            }
            throw new BeanNotOfRequiredTypeException(name, requiredType, bean.getClass());
        }
    }
    return (T) bean;
}
  1. 进入createBean方法中:
protected Object createBean(String beanName, RootBeanDefinition mbd, @Nullable Object[] args) throws BeanCreationException {
    if (logger.isTraceEnabled()) {
        logger.trace("Creating instance of bean '" + beanName + "'");
    }
    RootBeanDefinition mbdToUse = mbd;
    // Make sure bean class is actually resolved at this point, and
    // clone the bean definition in case of a dynamically resolved Class
    // which cannot be stored in the shared merged bean definition.
    // 确保此时确实解析了 Bean 类,并在动态解析的类无法存储在共享合并的 Bean 定义中的情况下克隆 Bean 定义。
    Class<?> resolvedClass = resolveBeanClass(mbd, beanName);
    if (resolvedClass != null && !mbd.hasBeanClass() && mbd.getBeanClassName() != null) {
        mbdToUse = new RootBeanDefinition(mbd);
        mbdToUse.setBeanClass(resolvedClass);
    }
    // Prepare method overrides.
    try {
        mbdToUse.prepareMethodOverrides();
    } catch (BeanDefinitionValidationException ex) {
        throw new BeanDefinitionStoreException(mbdToUse.getResourceDescription(), beanName, "Validation of method overrides failed", ex);
    }
    try {
        // Give BeanPostProcessors a chance to return a proxy instead of the target bean instance.
        // 让 BeanPostProcessor 有机会返回代理而不是目标 Bean 实例。
        Object bean = resolveBeforeInstantiation(beanName, mbdToUse);
        if (bean != null) {
            return bean;
        }
    } catch (Throwable ex) {
        throw new BeanCreationException(mbdToUse.getResourceDescription(), beanName, "BeanPostProcessor before instantiation of bean failed", ex);
    }
    try {
        Object beanInstance = doCreateBean(beanName, mbdToUse, args);
        if (logger.isTraceEnabled()) {
            logger.trace("Finished creating instance of bean '" + beanName + "'");
        }
        return beanInstance;
    } catch (BeanCreationException | ImplicitlyAppearedSingletonException ex) {
        // A previously detected exception with proper bean creation context already,
        // or illegal singleton state to be communicated up to DefaultSingletonBeanRegistry.
        throw ex;
    } catch (Throwable ex) {
        throw new BeanCreationException(mbdToUse.getResourceDescription(), beanName, "Unexpected exception during bean creation", ex);
    }
}
  1. 再进入到doCreateBean方法中:
protected Object doCreateBean(String beanName, RootBeanDefinition mbd, @Nullable Object[] args) throws BeanCreationException {
    // Instantiate the bean.
    BeanWrapper instanceWrapper = null;
    if (mbd.isSingleton()) {
        instanceWrapper = this.factoryBeanInstanceCache.remove(beanName);
    }
    if (instanceWrapper == null) {
        //创建好你自定义的创建bean的方式的bean
        instanceWrapper = createBeanInstance(beanName, mbd, args);
    }
    Object bean = instanceWrapper.getWrappedInstance();
    //获取创建好的bean的Class也就是beanType
    Class<?> beanType = instanceWrapper.getWrappedClass();
    //判断当前创建出来的bean是否为null
    if (beanType != NullBean.class) {
        //不为null的话就将当前的beanType赋值给RootBeanDefinition
        mbd.resolvedTargetType = beanType;
    }
    // Allow post-processors to modify the merged bean definition. 允许后处理器修改合并的 Bean 定义。
    synchronized (mbd.postProcessingLock) {
        if (!mbd.postProcessed) {
            try {
                applyMergedBeanDefinitionPostProcessors(mbd, beanType, beanName);
            } catch (Throwable ex) {
                throw new BeanCreationException(mbd.getResourceDescription(), beanName, "Post-processing of merged bean definition failed", ex);
            }
            mbd.postProcessed = true;
        }
    }
    // Eagerly cache singletons to be able to resolve circular references
    // even when triggered by lifecycle interfaces like BeanFactoryAware.
    // 急切地缓存单例,以便能够解析循环引用,即使由生命周期接口(如 BeanFactoryAware)触发也是如此。
    boolean earlySingletonExposure = (mbd.isSingleton() && this.allowCircularReferences && isSingletonCurrentlyInCreation(beanName));
    if (earlySingletonExposure) {
        if (logger.isTraceEnabled()) {
            logger.trace("Eagerly caching bean '" + beanName +
                    "' to allow for resolving potential circular references");
        }
        addSingletonFactory(beanName, () -> getEarlyBeanReference(beanName, mbd, bean));
    }

    // Initialize the bean instance. 初始化 Bean 实例。
    Object exposedObject = bean;
    try {
        // 属性填充
        populateBean(beanName, mbd, instanceWrapper);
        exposedObject = initializeBean(beanName, exposedObject, mbd);
    } catch (Throwable ex) {
        if (ex instanceof BeanCreationException && beanName.equals(((BeanCreationException) ex).getBeanName())) {
            throw (BeanCreationException) ex;
        } else {
            throw new BeanCreationException(
                    mbd.getResourceDescription(), beanName, "Initialization of bean failed", ex);
        }
    }
    if (earlySingletonExposure) {
        Object earlySingletonReference = getSingleton(beanName, false);
        if (earlySingletonReference != null) {
            if (exposedObject == bean) {
                exposedObject = earlySingletonReference;
            } else if (!this.allowRawInjectionDespiteWrapping && hasDependentBean(beanName)) {
                String[] dependentBeans = getDependentBeans(beanName);
                Set<String> actualDependentBeans = new LinkedHashSet<>(dependentBeans.length);
                for (String dependentBean : dependentBeans) {
                    if (!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.");
                }
            }
        }
    }
    // Register bean as disposable.
    try {
        registerDisposableBeanIfNecessary(beanName, bean, mbd);
    } catch (BeanDefinitionValidationException ex) {
        throw new BeanCreationException(mbd.getResourceDescription(), beanName, "Invalid destruction signature", ex);
    }
    return exposedObject;
}
  1. 从这里开始正真的开始创建bean实例了:我们可以看到在上述代码的第9行中调用了createBeanInstance(beanName, mbd, args)方法来创建一个bean实例
protected BeanWrapper createBeanInstance(String beanName, RootBeanDefinition mbd, @Nullable Object[] args) {
    // Make sure bean class is actually resolved at this point.
    Class<?> beanClass = resolveBeanClass(mbd, beanName);
    if (beanClass != null && !Modifier.isPublic(beanClass.getModifiers()) && !mbd.isNonPublicAccessAllowed()) {
        throw new BeanCreationException(mbd.getResourceDescription(), beanName, "Bean class isn't public, and non-public access not allowed: " + beanClass.getName());
    }
    Supplier<?> instanceSupplier = mbd.getInstanceSupplier();
    if (instanceSupplier != null) {
        return obtainFromSupplier(instanceSupplier, beanName);
    }
    if (mbd.getFactoryMethodName() != null) {
        return instantiateUsingFactoryMethod(beanName, mbd, args);
    }
    // Shortcut when re-creating the same bean...
    boolean resolved = false;
    boolean autowireNecessary = false;
    if (args == null) {
        synchronized (mbd.constructorArgumentLock) {
            if (mbd.resolvedConstructorOrFactoryMethod != null) {
                resolved = true;
                autowireNecessary = mbd.constructorArgumentsResolved;
            }
        }
    }
    if (resolved) {
        if (autowireNecessary) {
            return autowireConstructor(beanName, mbd, null, null);
        } else {
            return instantiateBean(beanName, mbd);
        }
    }
    // Candidate constructors for autowiring?
    Constructor<?>[] ctors = determineConstructorsFromBeanPostProcessors(beanClass, beanName);
    if (
            ctors != null ||
                    mbd.getResolvedAutowireMode() == AUTOWIRE_CONSTRUCTOR ||
                    mbd.hasConstructorArgumentValues() ||
                    !ObjectUtils.isEmpty(args)
    ) {
        return autowireConstructor(beanName, mbd, ctors, args);
    }
    // Preferred constructors for default construction? 默认构造的首选构造函数?
    ctors = mbd.getPreferredConstructors();
    if (ctors != null) {
        return autowireConstructor(beanName, mbd, ctors, null);
    }
    // No special handling: simply use no-arg constructor.
    return instantiateBean(beanName, mbd);
}
  1. 可以看到我在第33行高光了,determineConstructorsFromBeanPostProcessors方法进去看看:
protected Constructor<?>[] determineConstructorsFromBeanPostProcessors(@Nullable Class<?> beanClass, String beanName) 
																		throws BeansException {
    if (beanClass != null && hasInstantiationAwareBeanPostProcessors()) {
        for (BeanPostProcessor bp : getBeanPostProcessors()) {
            // 判断当前的beanPostProcessor是否是SmartInstantiationAwareBeanPostProcessor
            if (bp instanceof SmartInstantiationAwareBeanPostProcessor) {
                SmartInstantiationAwareBeanPostProcessor ibp = (SmartInstantiationAwareBeanPostProcessor) bp;
                // 调用determineCandidateConstructors方法去推断构造器
                Constructor<?>[] ctors = ibp.determineCandidateConstructors(beanClass, beanName);
                if (ctors != null) {
                    return ctors;
                }
            }
        }
    }
    return null;
}
  1. 好的目前为止,咱们看到第一个beanPostProcessor接口--SmartInstantiationAwareBeanPostProcessor在这里要被扫描执行。
  2. 然后咱们继续看在doCreateBean方法中第23行applyMergedBeanDefinitionPostProcessors(mbd, beanType, beanName)方法:
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);
        }
    }
}
  1. 好的这里咱们又看到一个BeanPostProcessor接口的实现类MergedBeanDefinitionPostProcessor被调用了。
  2. 咱们再往下走到populateBean(beanName, mbd, instanceWrapper);到bean的属性填充方法中:
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.
    // 让任何 InstantiationAwareBeanPostProcessor 有机会在设置属性之前修改 Bean 的状态。例如,这可用于支持字段注入样式。
    if (!mbd.isSynthetic() && hasInstantiationAwareBeanPostProcessors()) {
        for (BeanPostProcessor bp : getBeanPostProcessors()) {
            if (bp instanceof InstantiationAwareBeanPostProcessor) {
                InstantiationAwareBeanPostProcessor ibp = (InstantiationAwareBeanPostProcessor) bp;
                if (!ibp.postProcessAfterInstantiation(bw.getWrappedInstance(), beanName)) {
                    return;
                }
            }
        }
    }
    PropertyValues pvs = (mbd.hasPropertyValues() ? mbd.getPropertyValues() : null);
    int resolvedAutowireMode = mbd.getResolvedAutowireMode();
    if (resolvedAutowireMode == AUTOWIRE_BY_NAME || resolvedAutowireMode == AUTOWIRE_BY_TYPE) {
        MutablePropertyValues newPvs = new MutablePropertyValues(pvs);
        // Add property values based on autowire by name if applicable.
        // 如果适用,请按名称添加基于自动连线的属性值。
        if (resolvedAutowireMode == AUTOWIRE_BY_NAME) {
            autowireByName(beanName, mbd, bw, newPvs);
        }
        // Add property values based on autowire by type if applicable.
        // 如果适用,请按类型添加基于自动连线的属性值。
        if (resolvedAutowireMode == 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);
    }
}
  1. 在populateBean方法的16~23行中对beanPostProcessor接口的实现类InstantiationAwareBeanPostProcessor进行处理。其实咱们可以看到在上述代码高亮处中,它发现它会先调用InstantiationAwareBeanPostProcessor接口的中postProcessAfterInstantiation方法来判断是否为true如果是则取反,则跳过return,但如果是false的话取反就直接return,说明InstantiationAwareBeanPostProcessor接口的其中的一项能力就是来判断当前的bean在实例化的时候是否需要执行某些beanPostProcessor接口的子实现类。
  2. 下面的一些beanPostProcessor接口的子实现就先到这里再说,我们下面试着使用populateBean属性填充时执行的InstantiationAwareBeanPostProcessor来玩一下。来验证我们15节点说的beanPostProcessor接口提供的两个接口方法的作用。
  3. 下面为了demo演示的代码组成:
@Configurable
@ComponentScan("com.lukp.registerBeanPostProcessors")
public class Config {
}
public class X {
}
public class Y {
	@Autowired
	X x;

	public void printf() {
		System.out.println("x:" + x);
	}
}
public class MyInstantiationAwareBeanPostProcessor implements InstantiationAwareBeanPostProcessor {
	@Override
	public boolean postProcessAfterInstantiation(Object bean, String beanName) throws BeansException {
		return false;
	}
}
public class Starter {
	public static void main(String[] args) {
		AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext();
		context.register(X.class, Y.class);
		context.refresh();
		Y y = context.getBean(Y.class);
		y.printf();
	}
}
  1. 当前我们看在上述的代码结构,咱们有两个Bean--Y--X,然后通过Config类将这两个Bean扫描到spring容器中。
  2. 同时我们还实现了InstantiationAwareBeanPostProcessor接口并且重写接口方法postProcessAfterInstantiation返回了false。
  3. 然后我们看启动类,很简单就是先创建了一个spring容器,然后再将类X和类Y注入到spring容器中,再获取一下Y,调用y的printf方法。
  4. 依据上述的所说咱们这里实现了InstantiationAwareBeanPostProcessor接口,并且重写方法postProcessAfterInstantiation方法将它的值设置为了false。
  5. 并且我们都知道,bean的依赖注入是在属性注入populateBean方法的时候做的,那么我现在没有将我自己实现的MyInstantiationAwareBeanPostProcessor注入到spring容器中,那么对应的最后输出的信息类X是不会为空的:

  1. 但是当我们将MyInstantiationAwareBeanPostProcessor也注入到spring容器中:
public class Starter {
	public static void main(String[] args) {
		AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext();
		context.register(X.class, Y.class, MyInstantiationAwareBeanPostProcessor.class);
		context.refresh();
		Y y = context.getBean(Y.class);
		y.printf();
	}
}
  1. 按照道理来说这个时候程序走到属性填充populateBean方法的19行的时候就会判断出好像有人修改了postProcessAfterInstantiation方法的默认值变成了false,那么就会直接return不会去执行下述的方式,当然对应的依赖注入也不会完成,所以最后类B的也会为null,下面我们来看看上述的理论是否是正确的?

  1. 我可以看到上述的图片就是咱们Dubug到属性填充方法populateBean中的一段源码,可以看到执行到咱们自己实现的MyInstantiationAwareBeanPostProcessor的时候:下面的判断为true所以直接return了。
if (!ibp.postProcessAfterInstantiation(bw.getWrappedInstance(), beanName)) {
    return;
}
  1. 那么对应的下面的依赖注入都不会成功所以最后咱们看看结果A类中的printf方法输出是不是为null:

  1. 确实是符合我们的期望的。

下面我们通过registerBeanPostProcessors说说Spring中的AOP是怎么做的:

  1. 先找到BeanPostProcessor接口下的实现类:AnnotationAwareAspectJAutoProxyCreator

public class AnnotationAwareAspectJAutoProxyCreator extends AspectJAwareAdvisorAutoProxyCreator
public class AspectJAwareAdvisorAutoProxyCreator extends AbstractAdvisorAutoProxyCreator
public abstract class AbstractAdvisorAutoProxyCreator extends AbstractAutoProxyCreator
public abstract class AbstractAutoProxyCreator extends ProxyProcessorSupport 
											   implements SmartInstantiationAwareBeanPostProcessor, BeanFactoryAware
public interface SmartInstantiationAwareBeanPostProcessor extends InstantiationAwareBeanPostProcessor 
public interface InstantiationAwareBeanPostProcessor extends BeanPostProcessor 
  1. 上述为AnnotationAwareAspectJAutoProxyCreator最终实现到BeanPostProcessor接口的流程。
  2. 那么对于该类我们的描述就是实现AOP动态代理的实现,我们现在要注意的一点是spring中有数不胜数的BeanPostProcessor接口的实现类,那么我们不可能全部都要执行一遍,那样的话我们的spring就完了,跑不起来了 。
  3. 这里我们稍微的说一下spring的AOP是怎么做的,以后会细说。
  4. 首先:我们看到在BeanPostProcessor接口下有两个接口方法:
public interface BeanPostProcessor {

	/**
	 * Apply this {@code BeanPostProcessor} to the given new bean instance <i>before</i> any bean
	 * initialization callbacks (like InitializingBean's {@code afterPropertiesSet}
	 * or a custom init-method). The bean will already be populated with property values.
	 * The returned bean instance may be a wrapper around the original.
	 * <p>The default implementation returns the given {@code bean} as-is.
	 * @param bean the new bean instance
	 * @param beanName the name of the bean
	 * @return the bean instance to use, either the original or a wrapped one;
	 * if {@code null}, no subsequent BeanPostProcessors will be invoked
	 * @throws org.springframework.beans.BeansException in case of errors
	 * @see org.springframework.beans.factory.InitializingBean#afterPropertiesSet
	 */
	@Nullable
	default Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
		return bean;
	}

	/**
	 * Apply this {@code BeanPostProcessor} to the given new bean instance <i>after</i> any bean
	 * initialization callbacks (like InitializingBean's {@code afterPropertiesSet}
	 * or a custom init-method). The bean will already be populated with property values.
	 * The returned bean instance may be a wrapper around the original.
	 * <p>In case of a FactoryBean, this callback will be invoked for both the FactoryBean
	 * instance and the objects created by the FactoryBean (as of Spring 2.0). The
	 * post-processor can decide whether to apply to either the FactoryBean or created
	 * objects or both through corresponding {@code bean instanceof FactoryBean} checks.
	 * <p>This callback will also be invoked after a short-circuiting triggered by a
	 * {@link InstantiationAwareBeanPostProcessor#postProcessBeforeInstantiation} method,
	 * in contrast to all other {@code BeanPostProcessor} callbacks.
	 * <p>The default implementation returns the given {@code bean} as-is.
	 * @param bean the new bean instance
	 * @param beanName the name of the bean
	 * @return the bean instance to use, either the original or a wrapped one;
	 * if {@code null}, no subsequent BeanPostProcessors will be invoked
	 * @throws org.springframework.beans.BeansException in case of errors
	 * @see org.springframework.beans.factory.InitializingBean#afterPropertiesSet
	 * @see org.springframework.beans.factory.FactoryBean
	 */
	@Nullable
	default Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
		return bean;
	}

}
  1. 我们主要是去看在实现AOP的postProcessor中在哪里实现了postProcessAfterInitialization方法。
  2. 现在我们回看AbstractAutoProxyCreator类,它是通过SmartInstantiationAwareBeanPostProcessor接口间接实现了BeanPostProcessor接口,并且实现了postProcessAfterInitialization接口:
/**
 * Create a proxy with the configured interceptors if the bean is identified as one to proxy by the subclass.
 * 如果 Bean 被子类标识为要代理的 Bean,则使用配置的拦截器创建代理。
 * @see #getAdvicesAndAdvisorsForBean
 */
@Override
public Object postProcessAfterInitialization(@Nullable Object bean, String beanName) {
    if (bean != null) {
        Object cacheKey = getCacheKey(bean.getClass(), beanName);
        if (this.earlyProxyReferences.remove(cacheKey) != bean) {
            // 完成代理
            return wrapIfNecessary(bean, beanName, cacheKey);
        }
    }
    return bean;
}
  1. 我们具体看看wrapIfNecessary中是如何完成动态代理的:
/**
 * Wrap the given bean if necessary, i.e. if it is eligible for being proxied.
 * 如有必要,包装给定的 bean,即它是否有资格被代理。
 * @param bean     the raw bean instance
 * @param beanName the name of the bean
 * @param cacheKey the cache key for metadata access
 * @return a proxy wrapping the bean, or the raw bean instance as-is
 */
protected Object wrapIfNecessary(Object bean, String beanName, Object cacheKey) {
    if (StringUtils.hasLength(beanName) && this.targetSourcedBeans.contains(beanName)) {
        return bean;
    }
    if (Boolean.FALSE.equals(this.advisedBeans.get(cacheKey))) {
        return bean;
    }
    if (isInfrastructureClass(bean.getClass()) || shouldSkip(bean.getClass(), beanName)) {
        this.advisedBeans.put(cacheKey, Boolean.FALSE);
        return bean;
    }
    // Create proxy if we have advice.
    Object[] specificInterceptors = getAdvicesAndAdvisorsForBean(bean.getClass(), beanName, null);
    if (specificInterceptors != DO_NOT_PROXY) {
        this.advisedBeans.put(cacheKey, Boolean.TRUE);
        Object proxy = createProxy(
                bean.getClass(),
                beanName,
                specificInterceptors,
                new SingletonTargetSource(bean)
        );
        this.proxyTypes.put(cacheKey, proxy.getClass());
        return proxy;
    }
    this.advisedBeans.put(cacheKey, Boolean.FALSE);
    return bean;
}
  1. 在上述代码的24~29创建代理类,我们继续深入一下看看它的createProxy()方法:
/**
 * Create an AOP proxy for the given bean.
 * @param beanClass            the class of the bean
 * @param beanName             the name of the bean
 * @param specificInterceptors the set of interceptors that is
 *                             specific to this bean (may be empty, but not null)
 * @param targetSource         the TargetSource for the proxy,
 *                             already pre-configured to access the bean
 * @return the AOP proxy for the bean
 * @see #buildAdvisors
 */
protected Object createProxy(Class<?> beanClass,
                             @Nullable String beanName,
                             @Nullable Object[] specificInterceptors,
                             TargetSource targetSource) {
    if (this.beanFactory instanceof ConfigurableListableBeanFactory) {
        AutoProxyUtils.exposeTargetClass((ConfigurableListableBeanFactory) this.beanFactory, beanName, beanClass);
    }
    ProxyFactory proxyFactory = new ProxyFactory();
    proxyFactory.copyFrom(this);
    if (proxyFactory.isProxyTargetClass()) {
        // Explicit handling of JDK proxy targets (for introduction advice scenarios)
        if (Proxy.isProxyClass(beanClass)) {
            // Must allow for introductions; can't just set interfaces to the proxy's interfaces only.
            for (Class<?> ifc : beanClass.getInterfaces()) {
                proxyFactory.addInterface(ifc);
            }
        }
    } else {
        // No proxyTargetClass flag enforced, let's apply our default checks...
        if (shouldProxyTargetClass(beanClass, beanName)) {
            proxyFactory.setProxyTargetClass(true);
        } else {
            evaluateProxyInterfaces(beanClass, proxyFactory);
        }
    }
    Advisor[] advisors = buildAdvisors(beanName, specificInterceptors);
    proxyFactory.addAdvisors(advisors);
    proxyFactory.setTargetSource(targetSource);
    customizeProxyFactory(proxyFactory);
    proxyFactory.setFrozen(this.freezeProxy);
    if (advisorsPreFiltered()) {
        proxyFactory.setPreFiltered(true);
    }
    return proxyFactory.getProxy(getProxyClassLoader());
}
  1. 点进高光处:proxyFactory.getProxy(getProxyClassLoader());
public Object getProxy(@Nullable ClassLoader classLoader) {
    return createAopProxy().getProxy(classLoader);
}

  1. 调用Idea的快捷键我们发现spring对于代理类的生成方式就是咱们平时说的两种:CGLib和JDK两种不同形式的代理方式。
  2. 然后点进getProxy()方法前面的方法:createAopProxy()方法:
/**
 * Subclasses should call this to get a new AOP proxy. 子类应该调用它来获得一个新的AOP代理。
 * They should <b>not</b>
 * create an AOP proxy with {@code this} as an argument.
 */
protected final synchronized AopProxy createAopProxy() {
    if (!this.active) {
        activate();
    }
    return getAopProxyFactory().createAopProxy(this);
}

点进createAopProxy(this)方法中:

public AopProxy createAopProxy(AdvisedSupport config) throws AopConfigException {
    if (config.isOptimize() || config.isProxyTargetClass() || hasNoUserSuppliedProxyInterfaces(config)) {
        Class<?> targetClass = config.getTargetClass();
        if (targetClass == null) {
            throw new AopConfigException("TargetSource cannot determine target class: " +
                    "Either an interface or a target is required for proxy creation.");
        }
        if (targetClass.isInterface() || Proxy.isProxyClass(targetClass)) {
            return new JdkDynamicAopProxy(config);
        }
        return new ObjenesisCglibAopProxy(config);
    }
    else {
        return new JdkDynamicAopProxy(config);
    }
}
  1. 可以看到这里在8~15行,是在判断当前被代理类的类的类型是什么?如果是interface也就是接口类型就会走到第一个if块中,也就是走的默认的JDK的动态代理过程。
  2. 回到getProxy方法,再次点击进入到JDK的动态代理的实现中:
@Override
public Object getProxy(@Nullable ClassLoader classLoader) {
    if (logger.isTraceEnabled()) {
        logger.trace("Creating JDK dynamic proxy: " + this.advised.getTargetSource());
    }
    Class<?>[] proxiedInterfaces = AopProxyUtils.completeProxiedInterfaces(this.advised, true);
    findDefinedEqualsAndHashCodeMethods(proxiedInterfaces);
    return Proxy.newProxyInstance(classLoader, proxiedInterfaces, this);
}
  1. 最后高光的这段代码是不是很属性就是调用JDK提供的java.lang.reflect包下的newProxyInstance()方法将当前需要被代理的类,代理为一个代理对象。
  2. 然后我们现在回过头来看,spring中有那么多的beanPostprocessor接口spring是不可能将这些接口的实现类一个一个都去执行一遍,那就完了跑不起来了,那么针对于当前AOP动态代理的内容来说,我们只需要去实现AnnotationAwareAspectJAutoProxyCreator这个子实现即可完成对于一个Bean代理类的生成动作。
  3. 在refrash中的registerBeanPostProcessors(beanFactory);方法中:
/**
 * Instantiate and register all BeanPostProcessor beans,respecting explicit order if given.
 * 实例化并注册所有 BeanPostProcessor bean,如果给定,则遵守显式顺序。
 * <p>Must be called before any instantiation of application beans.
 */
protected void registerBeanPostProcessors(ConfigurableListableBeanFactory beanFactory) {
    PostProcessorRegistrationDelegate.registerBeanPostProcessors(beanFactory, this);
}
/**
 * 该方法就是来处理我们注入进来的beanPostProcessor
 * @param beanFactory
 * @param applicationContext
 */
public static void registerBeanPostProcessors(
        ConfigurableListableBeanFactory beanFactory,
        AbstractApplicationContext applicationContext) {
    /**
     * 在这里就会通过beanName在BDMaps中找到所有的beanPostProcessor,但是要注意的一点是这里找出来的bean不是都实例化好的
     */
    String[] postProcessorNames = beanFactory.getBeanNamesForType(BeanPostProcessor.class, true, false);
    // Register BeanPostProcessorChecker that logs an info message when
    // a bean is created during BeanPostProcessor instantiation, i.e. when
    // a bean is not eligible for getting processed by all BeanPostProcessors.
    int beanProcessorTargetCount = beanFactory.getBeanPostProcessorCount() + 1 + postProcessorNames.length;
    beanFactory.addBeanPostProcessor(new BeanPostProcessorChecker(beanFactory, beanProcessorTargetCount));

    // Separate between BeanPostProcessors that implement PriorityOrdered,
    // Ordered, and the rest.
    List<BeanPostProcessor> priorityOrderedPostProcessors = new ArrayList<>();
    List<BeanPostProcessor> internalPostProcessors = new ArrayList<>();
    List<String> orderedPostProcessorNames = new ArrayList<>();
    List<String> nonOrderedPostProcessorNames = new ArrayList<>();
    for (String ppName : postProcessorNames) {
        if (beanFactory.isTypeMatch(ppName, PriorityOrdered.class)) {
            BeanPostProcessor pp = beanFactory.getBean(ppName, BeanPostProcessor.class);
            priorityOrderedPostProcessors.add(pp);
            if (pp instanceof MergedBeanDefinitionPostProcessor) {
                internalPostProcessors.add(pp);
            }
        }
        else if (beanFactory.isTypeMatch(ppName, Ordered.class)) {
            orderedPostProcessorNames.add(ppName);
        }
        else {
            nonOrderedPostProcessorNames.add(ppName);
        }
    }

    // First, register the BeanPostProcessors that implement PriorityOrdered.
    sortPostProcessors(priorityOrderedPostProcessors, beanFactory);
    /**
     * 当我们想要实现AOP的动态代理的时候可以使用AnnotationAwareAspectJAutoProxyCreator,并且假如说我们就有,
     * 在下面的registerBeanPostProcessors中就会将当我们想要实现AOP的动态代理的时候可以使用AnnotationAwareAspectJAutoProxyCreator add
     * 到一个 private final List<BeanPostProcessor> beanPostProcessors = new CopyOnWriteArrayList<>();集合中
     */
    registerBeanPostProcessors(beanFactory, priorityOrderedPostProcessors);

    // Next, register the BeanPostProcessors that implement Ordered.
    List<BeanPostProcessor> orderedPostProcessors = new ArrayList<>(orderedPostProcessorNames.size());
    for (String ppName : orderedPostProcessorNames) {
        BeanPostProcessor pp = beanFactory.getBean(ppName, BeanPostProcessor.class);
        orderedPostProcessors.add(pp);
        if (pp instanceof MergedBeanDefinitionPostProcessor) {
            internalPostProcessors.add(pp);
        }
    }
    sortPostProcessors(orderedPostProcessors, beanFactory);
    registerBeanPostProcessors(beanFactory, orderedPostProcessors);

    // Now, register all regular BeanPostProcessors.
    List<BeanPostProcessor> nonOrderedPostProcessors = new ArrayList<>(nonOrderedPostProcessorNames.size());
    for (String ppName : nonOrderedPostProcessorNames) {
        BeanPostProcessor pp = beanFactory.getBean(ppName, BeanPostProcessor.class);
        nonOrderedPostProcessors.add(pp);
        if (pp instanceof MergedBeanDefinitionPostProcessor) {
            internalPostProcessors.add(pp);
        }
    }
    registerBeanPostProcessors(beanFactory, nonOrderedPostProcessors);

    // Finally, re-register all internal BeanPostProcessors.
    sortPostProcessors(internalPostProcessors, beanFactory);
    registerBeanPostProcessors(beanFactory, internalPostProcessors);

    // Re-register post-processor for detecting inner beans as ApplicationListeners,
    // moving it to the end of the processor chain (for picking up proxies etc).
    beanFactory.addBeanPostProcessor(new ApplicationListenerDetector(applicationContext));
}
/**
 * Register the given BeanPostProcessor beans. 注册给定的 BeanPostProcessor bean。
 */
private static void registerBeanPostProcessors(
        ConfigurableListableBeanFactory beanFactory,
        List<BeanPostProcessor> postProcessors) {
    for (BeanPostProcessor postProcessor : postProcessors) {
        beanFactory.addBeanPostProcessor(postProcessor);
    }
}
@Override
public void addBeanPostProcessor(BeanPostProcessor beanPostProcessor) {
    Assert.notNull(beanPostProcessor, "BeanPostProcessor must not be null");
    // Remove from old position, if any
    this.beanPostProcessors.remove(beanPostProcessor);
    // Track whether it is instantiation/destruction aware
    if (beanPostProcessor instanceof InstantiationAwareBeanPostProcessor) {
        this.hasInstantiationAwareBeanPostProcessors = true;
    }
    if (beanPostProcessor instanceof DestructionAwareBeanPostProcessor) {
        this.hasDestructionAwareBeanPostProcessors = true;
    }
    // Add to end of list
    this.beanPostProcessors.add(beanPostProcessor);
}

在上述代码的高光处第7行,判断当前循环的BeanPostProcessor是什么类型的,还记得嘛我们的AnnotationAwareAspectJAutoProxyCreator类是间接实现了InstantiationAwareBeanPostProcessor接口的,所以在进行类型判断的时候就会被添加到beanPostProcessors中。

private final List<BeanPostProcessor> beanPostProcessors = new CopyOnWriteArrayList<>();
  1. 然后在bean被实例化的生命周期中的会调用postProcessAfterInstantiation方法的时候会调用生成代理类的逻辑,也就是我们上面看JDK的动态代理的过程,会走到那里面实现代理类的生成。
  2. 然后在registerBeanPostProcessors()方法中完成对于实现BeanPostProcessor子类的回调处理。
  3. 下面咱们来稍微的讲一讲registerBeanPostProcessors的执行流程:
public static void registerBeanPostProcessors(ConfigurableListableBeanFactory beanFactory, AbstractApplicationContext applicationContext) {
    String[] postProcessorNames = beanFactory.getBeanNamesForType(BeanPostProcessor.class, true, false);
    // Register BeanPostProcessorChecker that logs an info message when
    // a bean is created during BeanPostProcessor instantiation, i.e. when
    // a bean is not eligible for getting processed by all BeanPostProcessors.
    int beanProcessorTargetCount = beanFactory.getBeanPostProcessorCount() + 1 + postProcessorNames.length;
    beanFactory.addBeanPostProcessor(new BeanPostProcessorChecker(beanFactory, beanProcessorTargetCount));

    // Separate between BeanPostProcessors that implement PriorityOrdered,
    // Ordered, and the rest.
    List<BeanPostProcessor> priorityOrderedPostProcessors = new ArrayList<>();
    List<BeanPostProcessor> internalPostProcessors = new ArrayList<>();
    List<String> orderedPostProcessorNames = new ArrayList<>();
    List<String> nonOrderedPostProcessorNames = new ArrayList<>();
    for (String ppName : postProcessorNames) {
        if (beanFactory.isTypeMatch(ppName, PriorityOrdered.class)) {
            BeanPostProcessor pp = beanFactory.getBean(ppName, BeanPostProcessor.class);
            priorityOrderedPostProcessors.add(pp);
            if (pp instanceof MergedBeanDefinitionPostProcessor) {
                internalPostProcessors.add(pp);
            }
        } else if (beanFactory.isTypeMatch(ppName, Ordered.class)) {
            orderedPostProcessorNames.add(ppName);
        } else {
            nonOrderedPostProcessorNames.add(ppName);
        }
    }

    // First, register the BeanPostProcessors that implement PriorityOrdered.
    sortPostProcessors(priorityOrderedPostProcessors, beanFactory);
    /**
     * 当我们想要实现AOP的动态代理的时候可以使用AnnotationAwareAspectJAutoProxyCreator,并且假如说我们就有,
     * 在下面的registerBeanPostProcessors中就会将当我们想要实现AOP的动态代理的时候可以使用AnnotationAwareAspectJAutoProxyCreator add
     * 到一个 private final List<BeanPostProcessor> beanPostProcessors = new CopyOnWriteArrayList<>();集合中
     */
    registerBeanPostProcessors(beanFactory, priorityOrderedPostProcessors);

    // Next, register the BeanPostProcessors that implement Ordered.
    List<BeanPostProcessor> orderedPostProcessors = new ArrayList<>(orderedPostProcessorNames.size());
    for (String ppName : orderedPostProcessorNames) {
        BeanPostProcessor pp = beanFactory.getBean(ppName, BeanPostProcessor.class);
        orderedPostProcessors.add(pp);
        if (pp instanceof MergedBeanDefinitionPostProcessor) {
            internalPostProcessors.add(pp);
        }
    }
    sortPostProcessors(orderedPostProcessors, beanFactory);
    registerBeanPostProcessors(beanFactory, orderedPostProcessors);

    // Now, register all regular BeanPostProcessors.
    List<BeanPostProcessor> nonOrderedPostProcessors = new ArrayList<>(nonOrderedPostProcessorNames.size());
    for (String ppName : nonOrderedPostProcessorNames) {
        BeanPostProcessor pp = beanFactory.getBean(ppName, BeanPostProcessor.class);
        nonOrderedPostProcessors.add(pp);
        if (pp instanceof MergedBeanDefinitionPostProcessor) {
            internalPostProcessors.add(pp);
        }
    }
    registerBeanPostProcessors(beanFactory, nonOrderedPostProcessors);

    // Finally, re-register all internal BeanPostProcessors.
    sortPostProcessors(internalPostProcessors, beanFactory);
    registerBeanPostProcessors(beanFactory, internalPostProcessors);

    // Re-register post-processor for detecting inner beans as ApplicationListeners,
    // moving it to the end of the processor chain (for picking up proxies etc).
    beanFactory.addBeanPostProcessor(new ApplicationListenerDetector(applicationContext));
}
  • 在上述代码的第一个高光处的作用是:会通过beanName在BDMaps中找到所有的beanPostProcessor,但是要注意的一点是这里找出来的bean不是都实例化好的。
    • 首先我们提供一个启动类:该启动类中我提供了一个我自己实现的类MyInstantiationAwareBeanPostProcessor。
public class Starter {
	public static void main(String[] args) {
		AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext();
		context.register(X.class, Y.class, MyInstantiationAwareBeanPostProcessor.class);
		context.refresh();
		Y y = context.getBean(Y.class);
		y.printf();
	}
}
    • 那么按照理想化的方式来说当前在调用registerBeanPostProcessors方法的时候就只会扫描出来一个咱们自定义的BeanPostProcessor接口我们通过DeBug看看:

    • 可以看到在当前的spring容器中实现了BeanPostProcessor接口并且扫描出来的只有三个,前面两个是spring内置的BeanPostProcessor接口实现类,再看下面一个是不是咱们自己实现的叫:MyInstantiationAwareBeanPostProcessor。
    • 然后再说一下spring这两个内置的BeanPostProcessor接口:
      • org.springframework.context.annotation.internalAutowiredAnnotationProcessor:从它的名字来解析,是针对于@AutoWrited注解的后置处理器。我们可以进去看看:
/**
 * Create a new {@code AutowiredAnnotationBeanPostProcessor} for Spring's
 * standard {@link Autowired @Autowired} and {@link Value @Value} annotations.
 * <p>Also supports JSR-330's {@link javax.inject.Inject @Inject} annotation,
 * if available.
 */
@SuppressWarnings("unchecked")
public AutowiredAnnotationBeanPostProcessor() {
    this.autowiredAnnotationTypes.add(Autowired.class);
    this.autowiredAnnotationTypes.add(Value.class);
    try {
        this.autowiredAnnotationTypes.add((Class<? extends Annotation>)
                ClassUtils.forName("javax.inject.Inject", AutowiredAnnotationBeanPostProcessor.class.getClassLoader()));
        logger.trace("JSR-330 'javax.inject.Inject' annotation found and supported for autowiring");
    }
    catch (ClassNotFoundException ex) {
        // JSR-330 API not available - simply skip.
    }
}
        • 可以看到AutowiredAnnotationBeanPostProcessor类的构造器中,就初始化了对于AnnotationType为Autowired和Value两个注解。
        • 然后在findAutowiredAnnotation方法中对autowiredAnnotationType进行判断是否是Autowired或者是Value,然后执行后续的动作。
@Nullable
private MergedAnnotation<?> findAutowiredAnnotation(AccessibleObject ao) {
    MergedAnnotations annotations = MergedAnnotations.from(ao);
    for (Class<? extends Annotation> type : this.autowiredAnnotationTypes) {
        MergedAnnotation<?> annotation = annotations.get(type);
        if (annotation.isPresent()) {
            return annotation;
        }
    }
    return null;
}
      • org.springframework.context.annotation.internalCommonAnnotationProcessor:该beanPostProcessor接口子实现类其内部很复杂简单来说,主要处理的是@Resource。
        • 看到在该后置处理器中:处理化了@PostConstruct注解和@PreDestroy注解。
public CommonAnnotationBeanPostProcessor() {
        setOrder(Ordered.LOWEST_PRECEDENCE - 3);
        setInitAnnotationType(PostConstruct.class);
        setDestroyAnnotationType(PreDestroy.class);
        ignoreResourceType("javax.xml.ws.WebServiceContext");
}
        • 并且在该类中在静态代码块中加入了@Resource注解。
static {
		webServiceRefClass = loadAnnotationType("javax.xml.ws.WebServiceRef");
		ejbClass = loadAnnotationType("javax.ejb.EJB");
		resourceAnnotationTypes.add(Resource.class);
		if (webServiceRefClass != null) {
			resourceAnnotationTypes.add(webServiceRefClass);
		}
		if (ejbClass != null) {
			resourceAnnotationTypes.add(ejbClass);
		}
	}
        • 在该类的buildResourceMetadata方法中对加了@Resource注解的类进行处理,这里截取buildResourceMetadata方法的一部分。
else if (field.isAnnotationPresent(Resource.class)) {
    if (Modifier.isStatic(field.getModifiers())) {
        throw new IllegalStateException("@Resource annotation is not supported on static fields");
    }
    if (!this.ignoredResourceTypes.contains(field.getType().getName())) {
        currElements.add(new ResourceElement(field, field, null));
    }
}
  • 上述咱们是提了一下,spring中内置实现的两个BeanPostProcessor接口的作用和是否真的将自己实现并且注入到spring容器中的BeanPostProcessor接口实现类,在registerBeanPostProcessors方法中扫描出来了。
  • 继续看下面的代码,也就是上述代码的第二处高光,该方法很重要具体是做什么的后面说,我们先说的它的组成:
// Register BeanPostProcessorChecker that logs an info message when
// a bean is created during BeanPostProcessor instantiation, i.e. when
// a bean is not eligible for getting processed by all BeanPostProcessors.
/**
* spring的注释翻译:注册 BeanPostProcessorChecker,该检查器在 BeanPostProcessor 实例化期间创建 Bean 时记录信息消息,
* 				  即当 Bean 不符合所有 BeanPostProcessor 处理的条件时。
* postProcessorNames.length:获取到这个的长度是没有如何问题就是看spring在经过一系列的扫描之后,得到postProcessor的集合的长度
* + 1:这个+1说的是spring中内置的BeanPostProcessorChecker它就必须存在的它是一个内部类实现了BeanPostProcessor接口的
* beanFactory.getBeanPostProcessorCount():这个就是spring考虑你通过API的方式在向spring容器中添加BeanPostProcessor接口的子实现(自己实现的)
* 将这三者加起来才算是完整的,当前的beanProcessorTargetCount
*/
int beanProcessorTargetCount = beanFactory.getBeanPostProcessorCount() + 1 + postProcessorNames.length;
beanFactory.addBeanPostProcessor(new BeanPostProcessorChecker(beanFactory, beanProcessorTargetCount));
  • 注释都写在上述的代码中,下面我们debug看看具体在BeanFactory中的情况:

  • 可以看到当前的beanPostProcessor(CopyOnWriteArrayList)集合中有三个对于bean的后置处理器:
    • ApplicationContextAwareProcessor
    • ApplicationListenerDetector
    • ImportAwareBeanPostProcessor(ConfigurationClassPostProcessor)
  1. 然后是BeanPostProcessorChecker这个BeanPostProcessor是干啥的呢?
  2. 它的作用是来检查当前执行BeanPostProcessor的前置和后置操作是否满足原先扫描的时候定义的执行次数。
  3. 下面咱们通过Debug来走一遍流程来看:
@Configurable
@ComponentScan(value = "com.lukp.registerBeanPostProcessors")
public class Config {
}
@Component
public class MyService {
	public void xx() {
		System.out.println("xxxxxx......");
	}
}
@Component
public class MyBeanPostProcessor implements BeanPostProcessor {

	public void printf() {
		System.out.println(" hello abcd ");
	}

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

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

}
  1. 可以看到在上面咱们有三个类:
  • Config:配置类,指定咱们扫描Bean的指定路径。
  • MyService:依托实验对象。
  • MyBeanPostProcessor:自定义实现的BeanPostProcessor。
  1. 下面咱们来详细的看看大致在整体的执行流程是咋走的,并且要讲清楚BeanPostProcessorChecker这个BeanPostProcessor是干啥的:
/**
 * BeanPostProcessor that logs an info message when a bean is created during
 * BeanPostProcessor instantiation, i.e. when a bean is not eligible for
 * getting processed by all BeanPostProcessors.
 * BeanPostProcessor,在创建bean期间记录信息消息BeanPostProcessor实例化,即当一个bean不符合条件时被所有BeanPostProcessors处理。
 */
private static final class BeanPostProcessorChecker implements BeanPostProcessor {

    private static final Log logger = LogFactory.getLog(BeanPostProcessorChecker.class);
    // Bean工厂
    private final ConfigurableListableBeanFactory beanFactory;
    // 记录当前Bean要被执行BeanPostProcessor的次数
    private final int beanPostProcessorTargetCount;

    public BeanPostProcessorChecker(ConfigurableListableBeanFactory beanFactory, int beanPostProcessorTargetCount) {
        this.beanFactory = beanFactory;
        this.beanPostProcessorTargetCount = beanPostProcessorTargetCount;
    }

    @Override
    public Object postProcessBeforeInitialization(Object bean, String beanName) {
        return bean;
    }

    @Override
    public Object postProcessAfterInitialization(Object bean, String beanName) {
        // 1.判断当前是否Bean的类型是否为BeanPostProcessor
        // 2.判断当前的Bean是否是为外部提供的BeanDefinition(回忆在将BeanDefinition中role字段)
        // 3.判断当前的执行的次数是否和预期的次数要少?
        if (
                !(bean instanceof BeanPostProcessor) &&
                        !isInfrastructureBean(beanName) &&
                        this.beanFactory.getBeanPostProcessorCount() < this.beanPostProcessorTargetCount
        ) {
            if (logger.isInfoEnabled()) {
                logger.info(
                        "Bean '" + beanName + "' of type [" + bean.getClass().getName() +
                                "] is not eligible for getting processed by all BeanPostProcessors " +
                                "(for example: not eligible for auto-proxying)"
                );
            }
        }
        return bean;
    }

    private boolean isInfrastructureBean(@Nullable String beanName) {
        if (beanName != null && this.beanFactory.containsBeanDefinition(beanName)) {
            BeanDefinition bd = this.beanFactory.getBeanDefinition(beanName);
            // RootBeanDefinition.ROLE_INFRASTRUCTURE:外部人员提供的BeanDefinition
            return (bd.getRole() == RootBeanDefinition.ROLE_INFRASTRUCTURE);
        }
        return false;
    }
}
  • 下面咱们截图到MyService的时候看一下:
  • 当前是咱们自己实现BeanPostProcessor的MyBeanPostProcessor类实现,按理来说我们自己实现的BeanPostProcessor是最晚执行的,所以说当前的MyBeanPostProcessor的执行时机对于MyService这个Bean来说是最晚的那个一个BeanPostProcessor。

  • 具体我们可以看堆栈的执行过程来清晰的看到MyService整体的执行流程:

    • 首先咱们看到在图片的下方红色方框框住的部分,是一个Bean在执行各种BeanPostProcessor接口的子实现的创建Bean的过程,但是要注意的一点是在当前红色方框中的执行过程Bean是没有被实例化的。

    • 然后我们说上面的两个红框,表示当前的Bean的实例对象已经被创建出来了,但是要执行applyBeanPostProcessorsBeforeInitialization,再执行postProcessBeforeInitialization,注意这里的含义是说明spring在执行bean的后置回调的时候是有顺序在执行回调的。
  • 回到咱们的主题,如果一个bean要被执行beanPostProcessor的动作的话,就一定会有一个BeanPostProcessor--BeanPostProcessorChecker,由此咱们看下面在执行applyBeanPostProcessorsBeforeInitialization回调的时候,在获取BeanPostProcessor的集合列表中,存在咱们所说的BeanPostProcessorChecker,通过这个结果导向说明当我们将一个Bean进行实例化的时候就必然会注册一个BeanPostProcessorChecker,来对当前的Bean在执行回调后置处理的时候进行执行次数的检查。

  • 下面的图中在执行了上面的applyBeanPostProcessorsBeforeInitialization方法,意味着当前Bean的所有的applyBeanPostProcessorsBeforeInitialization就被执行完成了。
@Override
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;
}
  • 然后就到applyBeanPostProcessorsAfterInitialization的后置执行了,也就是在initalizeBean的方法中的第二个红框中,它会执行当前Bean所有的后置回调。

  • ok,在执行后置的回调处理的时候就会执行注册的BeanPostProcessorChecker,检查啥呢?其实上面的代码中已经说过了但是在这里还是要说一下:
    • !(bean instanceof BeanPostProcessor):判断当前是否Bean的类型是否为BeanPostProcessor。
    • !isInfrastructureBean(beanName):判断当前的Bean是否是为外部提供的BeanDefinition(回忆在将BeanDefinition中role字段)。
    • this.beanFactory.getBeanPostProcessorCount() < this.beanPostProcessorTargetCount:判断当前的执行的次数是否和预期的次数要少?
    • 最后:当三个条件同时满足的时候,会打印日志但是并不会进行异常中断。
  • 那这里就奇怪了,我们一般做检查的话,肯定是会预料到这里会有一些问题,那么提前在这里做好异常捕获,即使的报错和输出日志,但是这里好像那件事都没有做(因为打印日志的级别是info并不是error),所以这里spring的作者到底是想要做什么呢?
  1. 下面咱们通过AOP的角度来解释这个问题,首先我们在配置类中开启AOP支持,添加@EnableAspectJAutoProxy注解:
@Configurable
@ComponentScan(value = "com.lukp.registerBeanPostProcessors")
@EnableAspectJAutoProxy
public class Config {
}
  1. 咱们先进入到@EnableAspectJAutoProxy注解内部:
class AspectJAutoProxyRegistrar implements ImportBeanDefinitionRegistrar {

	/**
	 * Register, escalate, and configure the AspectJ auto proxy creator based on the value
	 * of the @{@link EnableAspectJAutoProxy#proxyTargetClass()} attribute on the importing
	 *
	 * 根据导入时 @{@link EnableAspectJAutoProxy#proxyTargetClass()} 属性的值注册、升级和配置 AspectJ 自动代理创建器
	 * {@code @Configuration} class.
	 */
	@Override
	public void registerBeanDefinitions(AnnotationMetadata importingClassMetadata, BeanDefinitionRegistry registry) {
		AopConfigUtils.registerAspectJAnnotationAutoProxyCreatorIfNecessary(registry);
		AnnotationAttributes enableAspectJAutoProxy = AnnotationConfigUtils.attributesFor(importingClassMetadata, EnableAspectJAutoProxy.class);
		if (enableAspectJAutoProxy != null) {
			if (enableAspectJAutoProxy.getBoolean("proxyTargetClass")) {
				AopConfigUtils.forceAutoProxyCreatorToUseClassProxying(registry);
			}
			if (enableAspectJAutoProxy.getBoolean("exposeProxy")) {
				AopConfigUtils.forceAutoProxyCreatorToExposeProxy(registry);
			}
		}
	}

}
  1. 我们发现它是直接实现了ImportBeanDefinitionRegistrar,通过之前的学习我们可以知道的是Mybatis也是通过@Import注解直接导入一个MapperScannerRegistrar,其内部也是实现了ImportBeanDefinitionRegistrar接口,那么实现该接口也意味会直接将一个BeanDefinition注册到BeanDefinitionMap中去,下面看一下源码是怎么样的:
/**
 * Register, escalate, and configure the AspectJ auto proxy creator based on the value
 * of the @{@link EnableAspectJAutoProxy#proxyTargetClass()} attribute on the importing
 *
 * 根据导入时 @{@link EnableAspectJAutoProxy#proxyTargetClass()} 属性的值注册、升级和配置 AspectJ 自动代理创建器
 * {@code @Configuration} class.
 */
@Override
public void registerBeanDefinitions(AnnotationMetadata importingClassMetadata, BeanDefinitionRegistry registry) {
    AopConfigUtils.registerAspectJAnnotationAutoProxyCreatorIfNecessary(registry);
    AnnotationAttributes enableAspectJAutoProxy = AnnotationConfigUtils.attributesFor(importingClassMetadata, EnableAspectJAutoProxy.class);
    if (enableAspectJAutoProxy != null) {
        if (enableAspectJAutoProxy.getBoolean("proxyTargetClass")) {
            AopConfigUtils.forceAutoProxyCreatorToUseClassProxying(registry);
        }
        if (enableAspectJAutoProxy.getBoolean("exposeProxy")) {
            AopConfigUtils.forceAutoProxyCreatorToExposeProxy(registry);
        }
    }
}
@Nullable
public static BeanDefinition registerAspectJAnnotationAutoProxyCreatorIfNecessary(BeanDefinitionRegistry registry) {
    return registerAspectJAnnotationAutoProxyCreatorIfNecessary(registry, null);
}
@Nullable
public static BeanDefinition registerAspectJAnnotationAutoProxyCreatorIfNecessary(BeanDefinitionRegistry registry, @Nullable Object source) {
    return registerOrEscalateApcAsRequired(AnnotationAwareAspectJAutoProxyCreator.class, registry, source);
}
@Nullable
private static BeanDefinition registerOrEscalateApcAsRequired(Class<?> cls, BeanDefinitionRegistry registry, @Nullable Object source) {
    Assert.notNull(registry, "BeanDefinitionRegistry must not be null");
    if (registry.containsBeanDefinition(AUTO_PROXY_CREATOR_BEAN_NAME)) {
        BeanDefinition apcDefinition = registry.getBeanDefinition(AUTO_PROXY_CREATOR_BEAN_NAME);
        if (!cls.getName().equals(apcDefinition.getBeanClassName())) {
            int currentPriority = findPriorityForClass(apcDefinition.getBeanClassName());
            int requiredPriority = findPriorityForClass(cls);
            if (currentPriority < requiredPriority) {
                apcDefinition.setBeanClassName(cls.getName());
            }
        }
        return null;
    }
    RootBeanDefinition beanDefinition = new RootBeanDefinition(cls);
    beanDefinition.setSource(source);
    beanDefinition.getPropertyValues().add("order", Ordered.HIGHEST_PRECEDENCE);
    beanDefinition.setRole(BeanDefinition.ROLE_INFRASTRUCTURE);
    registry.registerBeanDefinition(AUTO_PROXY_CREATOR_BEAN_NAME, beanDefinition);
    return beanDefinition;
}
  1. 看到上述最后一个代码块中15~19行,创建了一个RootBeanDefinition,并且设置当前的BeanDefinition的源,设置它的propertyValueList,设置它的role为int ROLE_INFRASTRUCTURE = 2;表示当前的BeanDefinition是外部的也就是程序员设置进来的。
  2. 并且我们也可以做一个实验,当前在类Config加上@EnableAspectJAutoProxy注解之后在refresh方法中的registerBeanPostProcessors方法中的第一行代码的结果是多少有没有包含咱们AOP的相关的BeanPostProcessor:
String[] postProcessorNames = beanFactory.getBeanNamesForType(BeanPostProcessor.class, true, false);

  1. 发现确实在添加了@EnableAspectJAutoProxy注解之后多了一个后置处理器是关于AOP处理的。
  2. 回到话题spring为什么要做这个看似没啥用的日志提示,下面基于一个demo来说明这个问题:
@Configurable
@ComponentScan(value = "com.lukp.registerBeanPostProcessors")
@EnableAspectJAutoProxy
public class Config {
}
@Component
@Aspect
public class MyAspect {
    // 定义切点为MyService类
	@Pointcut("within(com.lukp.registerBeanPostProcessors.MyService)")
	public void pointcut() {
	}
	// 定义切面时机After,在拦截切面点后执行切面逻辑
	@After("pointcut()")
	public void aa() {
		System.out.println("The Aop against MyService is executed....");
	}
}
@Component
public class MyService {
	public void xx() {
		System.out.println("xxxxxx......");
	}
}
public class Starter {
	public static void main(String[] args) {
		AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(Config.class);
		context.getBean(MyService.class).xx();
	}
}
  1. 来我们看结果,按照预想,最后应该是先执行MyService中的xx方法中的话,然后才会执行切面类中的aa()方法的逻辑。

  1. 但是现在咱们变一下我们现在通过自定义实现的BeanPostProcessor--MyBeanPostProcessor来调用到MyService中的xx()方法,通过依赖注入的方式:
@Component
public class MyBeanPostProcessor implements BeanPostProcessor {

	@Autowired
	MyService myService;

	public void printf() {
		myService.xx();
	}

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

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

}

这个时候启动类也改为从MyBeanPostProcessor中调用myService中的xx()方法:

public class Starter {
	public static void main(String[] args) {
		AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(Config.class);
		context.getBean(MyBeanPostProcessor.class).printf();
	}
}
  1. 咱们看看结果:

  1. 可以看到虽然myservice中的aa()方法和切面中的后置切面也执行了,但是在执行前spring打印出了咱们现在在讨论的问题也就是上述图片中红色框的内容。
  2. 咱们仔细的看一下代码执行到BeanPostProcessorChecker中的postProcessAfterInitialization方法:

  1. 从上面的照片中可以看出确实在我们这么玩之后实际执行的次数和预计执行的次数不一样,所以应当输出相关的日志,可问题是到这里还是没有说明这段日志的输出有什么用呀,好的下面咱们来看看这种情况。
  2. 咱们现在将MyBeanPostProcessor修改一下,新增实现接口Ordered。
@Component
public class MyBeanPostProcessor implements BeanPostProcessor, Ordered {

	@Autowired
	MyService myService;

	public void printf() {
		myService.xx();
	}

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

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

	@Override
	public int getOrder() {
		return Ordered.HIGHEST_PRECEDENCE;
	}
}
  1. 这个时候咱们启动启动类:

  1. 我们发现Aop中的内容不起作用了!
  2. ko,现在咱们先不管当前的现象咱们接着往下看。
  3. 现在我们再将MyBeanPostProcessor改造一下:在该类中注入ApplicationContext,并且输出applicationContext,同时还创建了一个初始化方法init()。
@Component
public class MyBeanPostProcessor implements BeanPostProcessor {

	@Autowired
	MyService myService;
	@Autowired
	ApplicationContext applicationContext;

	@PostConstruct
	public void init() {
		System.out.println("MyBeanPostProcessor Init ...");
	}

	public void printf() {
		System.out.println("app--:" + applicationContext);
	}

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

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

}
  1. 这种情况下都是正常的,applicationContext是可以被注入进来的,并且初始化方法也是被正常执行的:

  1. 但是下面咱们加上一个接口:PriorityOrdered
@Component
public class MyBeanPostProcessor implements BeanPostProcessor, PriorityOrdered {

	@Autowired
	MyService myService;
	@Autowired
	ApplicationContext applicationContext;

	@PostConstruct
	public void init() {
		System.out.println("MyBeanPostProcessor Init ...");
	}

	public void printf() {
		System.out.println("app--:" + applicationContext);
		/*myService.xx();*/
	}

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

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

	@Override
	public int getOrder() {
		return Ordered.HIGHEST_PRECEDENCE;
	}
}
  1. 再次执行看结果:

  1. 我们发现不仅是applicationContext为null注入不进来,并且初始化方法也没有被执行,说明在实例化MyBeanPostProcessor的时候连正常Bean的生命周期都不走了。
  2. 那么现在咱们又把MyBeanPostProcessor改一下:
@Component
public class MyBeanPostProcessor implements BeanPostProcessor, ApplicationContextAware {

	@Autowired
	MyService myService;
	/*@Autowired
	ApplicationContext applicationContext;*/
	private ApplicationContext applicationContext;

	@PostConstruct
	public void init() {
		System.out.println("MyBeanPostProcessor Init ...");
	}

	public void printf() {
		System.out.println("app--:" + applicationContext);
	}

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

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

	@Override
	public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
		this.applicationContext =  applicationContext;
	}

}
  1. 通过实现ApplicationContextAware接口中的setApplicationContext方法来完成application的注入,看结果:

  1. 可以直接看到的是,applicationContext和初始化方法都执行了。
  2. 下面咱们开始一个一个的解析上述的"神奇现象":
  • 一:为什么在实现Ordered接口后,再执行代理对象的方法AOP就不生效了?
  • 二:为什么在实现PriorityOrdered接口后,初始化方法不生效了,也就是spring让当前的Bean干脆不走生命周期那一套了?
  • 三:为什么在实现PriorityOrdered接口后,applicationContext为null了,并且初始化方法不生效了?
  1. 解析:

  1. 我们大致可以看到上述的图中,整体registerBeanPostProcessors方法的扫描过程,下面用文字说一下上面咱们讨论的问题:
  • 其实核心代码很就在registerBeanPostProcessors方法上。
public static void registerBeanPostProcessors(ConfigurableListableBeanFactory beanFactory, AbstractApplicationContext applicationContext) {
    String[] postProcessorNames = beanFactory.getBeanNamesForType(BeanPostProcessor.class, true, false);
    // Register BeanPostProcessorChecker that logs an info message when
    // a bean is created during BeanPostProcessor instantiation, i.e. when
    // a bean is not eligible for getting processed by all BeanPostProcessors.
    int beanProcessorTargetCount = beanFactory.getBeanPostProcessorCount() + 1 + postProcessorNames.length;
    beanFactory.addBeanPostProcessor(new BeanPostProcessorChecker(beanFactory, beanProcessorTargetCount));

    // Separate between BeanPostProcessors that implement PriorityOrdered,Ordered, and the rest. 
    List<BeanPostProcessor> priorityOrderedPostProcessors = new ArrayList<>();
    List<BeanPostProcessor> internalPostProcessors = new ArrayList<>();
    List<String> orderedPostProcessorNames = new ArrayList<>();
    List<String> nonOrderedPostProcessorNames = new ArrayList<>();
    for (String ppName : postProcessorNames) {
        if (beanFactory.isTypeMatch(ppName, PriorityOrdered.class)) {
            BeanPostProcessor pp = beanFactory.getBean(ppName, BeanPostProcessor.class);
            priorityOrderedPostProcessors.add(pp);
            if (pp instanceof MergedBeanDefinitionPostProcessor) {
                internalPostProcessors.add(pp);
            }
        } else if (beanFactory.isTypeMatch(ppName, Ordered.class)) {
            orderedPostProcessorNames.add(ppName);
        } else {
            nonOrderedPostProcessorNames.add(ppName);
        }
    }

    // First, register the BeanPostProcessors that implement PriorityOrdered.
    sortPostProcessors(priorityOrderedPostProcessors, beanFactory);
    registerBeanPostProcessors(beanFactory, priorityOrderedPostProcessors);

    // Next, register the BeanPostProcessors that implement Ordered.
    List<BeanPostProcessor> orderedPostProcessors = new ArrayList<>(orderedPostProcessorNames.size());
    for (String ppName : orderedPostProcessorNames) {
        BeanPostProcessor pp = beanFactory.getBean(ppName, BeanPostProcessor.class);
        orderedPostProcessors.add(pp);
        if (pp instanceof MergedBeanDefinitionPostProcessor) {
            internalPostProcessors.add(pp);
        }
    }
    sortPostProcessors(orderedPostProcessors, beanFactory);
    registerBeanPostProcessors(beanFactory, orderedPostProcessors);

    // Now, register all regular BeanPostProcessors.
    List<BeanPostProcessor> nonOrderedPostProcessors = new ArrayList<>(nonOrderedPostProcessorNames.size());
    for (String ppName : nonOrderedPostProcessorNames) {
        BeanPostProcessor pp = beanFactory.getBean(ppName, BeanPostProcessor.class);
        nonOrderedPostProcessors.add(pp);
        if (pp instanceof MergedBeanDefinitionPostProcessor) {
            internalPostProcessors.add(pp);
        }
    }
    registerBeanPostProcessors(beanFactory, nonOrderedPostProcessors);

    // Finally, re-register all internal BeanPostProcessors.
    sortPostProcessors(internalPostProcessors, beanFactory);
    registerBeanPostProcessors(beanFactory, internalPostProcessors);

    // Re-register post-processor for detecting inner beans as ApplicationListeners,
    // moving it to the end of the processor chain (for picking up proxies etc).
    beanFactory.addBeanPostProcessor(new ApplicationListenerDetector(applicationContext));
}
  • 我们看到上述的代码前半部分大抵是在做BeanPostProcessor的分类:
    • priorityOrdered
    • internal
    • ordered
    • nonOrdered
  • 将这几类分类完成后,然后再将其一一处理,执行对应的BeanPostProcessor的实现。
  • 可以看到在15~21行是在判断当前的BeanPostProcessor的实现类是否实现了PriorityOrdered接口?
  • 如果实现了就将其add到priorityOrderedPostProcessors集合中,并且判断当前的BeanPostProcessor是否是MergedBeanDefinitionPostProcessor类型的,如果是则将其加入到internalPostProcessors集合中。
  • 下面继续判断当前的BeanPostProcessor是否实现了Ordered接口,如果实现了就会加入到orderedPostProcessorNames集合中,表示该BeanPostProcessor实现了Ordered接口。
  • 否则最后将剩余的BeanPostProcessor加入到nonOrderedPostProcessorNames,表示这些BeanPostProcessor是不需要进行排序的。
  • 好的,将所有扫描出来的beanPostProcessor扫描出来之后,下面马上开始的代码就比较重要了。
  • 在第29行对priorityOrderedPostProcessors集合中的BeanPostProcessor进行排序,然后在30行对priorityOrderedPostProcessors集合的BeanPostProcessor进行处理并加入到对应的BeanPostPrcossor集合中。
  • 下面执行的意思也是如此,对orderedPostProcessors集合进行排序并加入到对应的BeanPostPrcossor集合中,加入集合中的逻辑为:
private static void registerBeanPostProcessors(ConfigurableListableBeanFactory beanFactory, List<BeanPostProcessor> postProcessors) {
		for (BeanPostProcessor postProcessor : postProcessors) {
			beanFactory.addBeanPostProcessor(postProcessor);
		}
	}
@Override
public void addBeanPostProcessor(BeanPostProcessor beanPostProcessor) {
    Assert.notNull(beanPostProcessor, "BeanPostProcessor must not be null");
    // Remove from old position, if any
    this.beanPostProcessors.remove(beanPostProcessor);
    // Track whether it is instantiation/destruction aware
    if (beanPostProcessor instanceof InstantiationAwareBeanPostProcessor) {
        this.hasInstantiationAwareBeanPostProcessors = true;
    }
    if (beanPostProcessor instanceof DestructionAwareBeanPostProcessor) {
        this.hasDestructionAwareBeanPostProcessors = true;
    }
    // Add to end of list
    this.beanPostProcessors.add(beanPostProcessor);
}
  1. 至于为什么会发生加了PriorityOrdered接口之后就会发现初始化方法和自动注入失败了,原因就是因为执行的先后顺序被打乱了,由于在上述的代码中咱们可以看到priorityOrdered接口是第一个被处理的。
  2. 所以只要你实现了PriorityOrdered接口就会在这里处理后续的处理逻辑就结束了,所以相当于直接跳过了。