spring源码学习笔记之BeanPostProcessor(七)

1,108 阅读3分钟

处理完BeanFactoryPostProcessor后,接下来要处理的就是BeanPostProcessor,在refresh()方法中,调用 registerBeanPostProcessors 方法处理:

// Register bean processors that intercept bean creation.
// 注册bean处理器,这里只是注册功能,真正调用的是getBean方法
registerBeanPostProcessors(beanFactory);

BeanPostProcessors 的处理逻辑和 BeanFactoryPostProcessor 的处理逻辑类似,通过 beanFactory.getBeanNamesForType方法拿到 beanFactory 中的实现了BeanPostProcessor接口的类,然后按照 PriorityOrderedOrderednonOrdered的分类来处理。在registerBeanPostProcessors方法中只是注册功能,真正调用的是getBean方法。

public static void registerBeanPostProcessors(
        ConfigurableListableBeanFactory beanFactory, AbstractApplicationContext applicationContext) {

    // 找到所有实现了BeanPostProcessor接口的类
    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.
    // 记录下BeanPostProcessor的目标计数
    // 此处为什么要+1呢,原因非常简单,在此方法的最后会添加一个BeanPostProcessorChecker的类
    int beanProcessorTargetCount = beanFactory.getBeanPostProcessorCount() + 1 + postProcessorNames.length;
    // 添加BeanPostProcessorChecker(主要用于记录信息)到beanFactory中
    beanFactory.addBeanPostProcessor(new BeanPostProcessorChecker(beanFactory, beanProcessorTargetCount));

    // Separate between BeanPostProcessors that implement PriorityOrdered,
    // Ordered, and the rest.
    // 定义存放实现了PriorityOrdered接口的BeanPostProcessor集合
    List<BeanPostProcessor> priorityOrderedPostProcessors = new ArrayList<>();
    // 定义存放spring内部的BeanPostProcessor
    List<BeanPostProcessor> internalPostProcessors = new ArrayList<>();
    // 定义存放实现了Ordered接口的BeanPostProcessor的name集合
    List<String> orderedPostProcessorNames = new ArrayList<>();
    // 定义存放普通的BeanPostProcessor的name集合
    List<String> nonOrderedPostProcessorNames = new ArrayList<>();
    // 遍历beanFactory中存在的BeanPostProcessor的集合postProcessorNames,
    for (String ppName : postProcessorNames) {
        // 如果ppName对应的BeanPostProcessor实例实现了PriorityOrdered接口,则获取到ppName对应的BeanPostProcessor的实例添加到priorityOrderedPostProcessors中
        if (beanFactory.isTypeMatch(ppName, PriorityOrdered.class)) {
            BeanPostProcessor pp = beanFactory.getBean(ppName, BeanPostProcessor.class);
            priorityOrderedPostProcessors.add(pp);
            // 如果ppName对应的BeanPostProcessor实例也实现了MergedBeanDefinitionPostProcessor接口,那么则将ppName对应的bean实例添加到internalPostProcessors中
            if (pp instanceof MergedBeanDefinitionPostProcessor) {
                internalPostProcessors.add(pp);
            }
        }
        // 如果ppName对应的BeanPostProcessor实例没有实现PriorityOrdered接口,但是实现了Ordered接口,那么将ppName对应的bean实例添加到orderedPostProcessorNames中
        else if (beanFactory.isTypeMatch(ppName, Ordered.class)) {
            orderedPostProcessorNames.add(ppName);
        } else {
            // 否则将ppName添加到nonOrderedPostProcessorNames中
            nonOrderedPostProcessorNames.add(ppName);
        }
    }

    // First, register the BeanPostProcessors that implement PriorityOrdered.
    // 首先,对实现了PriorityOrdered接口的BeanPostProcessor实例进行排序操作
    sortPostProcessors(priorityOrderedPostProcessors, beanFactory);
    // 注册实现了PriorityOrdered接口的BeanPostProcessor实例添加到beanFactory中
    registerBeanPostProcessors(beanFactory, priorityOrderedPostProcessors);

    // Next, register the BeanPostProcessors that implement Ordered.
    // 注册所有实现Ordered的beanPostProcessor
    List<BeanPostProcessor> orderedPostProcessors = new ArrayList<>(orderedPostProcessorNames.size());
    for (String ppName : orderedPostProcessorNames) {
        // 根据ppName找到对应的BeanPostProcessor实例对象
        BeanPostProcessor pp = beanFactory.getBean(ppName, BeanPostProcessor.class);
        // 将实现了Ordered接口的BeanPostProcessor添加到orderedPostProcessors集合中
        orderedPostProcessors.add(pp);
        // 如果ppName对应的BeanPostProcessor实例也实现了MergedBeanDefinitionPostProcessor接口,那么则将ppName对应的bean实例添加到internalPostProcessors中
        if (pp instanceof MergedBeanDefinitionPostProcessor) {
            internalPostProcessors.add(pp);
        }
    }
    // 对实现了Ordered接口的BeanPostProcessor进行排序操作
    sortPostProcessors(orderedPostProcessors, beanFactory);
    //  注册实现了Ordered接口的BeanPostProcessor实例添加到beanFactory中
    registerBeanPostProcessors(beanFactory, orderedPostProcessors);

    // Now, register all regular BeanPostProcessors.
    // 创建存放没有实现PriorityOrdered和Ordered接口的BeanPostProcessor的集合
    List<BeanPostProcessor> nonOrderedPostProcessors = new ArrayList<>(nonOrderedPostProcessorNames.size());
    // 遍历集合
    for (String ppName : nonOrderedPostProcessorNames) {
        // 根据ppName找到对应的BeanPostProcessor实例对象
        BeanPostProcessor pp = beanFactory.getBean(ppName, BeanPostProcessor.class);
        // 将没有实现PriorityOrdered和Ordered接口的BeanPostProcessor添加到nonOrderedPostProcessors集合中
        nonOrderedPostProcessors.add(pp);
        // 如果ppName对应的BeanPostProcessor实例也实现了MergedBeanDefinitionPostProcessor接口,那么则将ppName对应的bean实例添加到internalPostProcessors中
        if (pp instanceof MergedBeanDefinitionPostProcessor) {
            internalPostProcessors.add(pp);
        }
    }
    //  注册没有实现PriorityOrdered和Ordered的BeanPostProcessor实例添加到beanFactory中
    registerBeanPostProcessors(beanFactory, nonOrderedPostProcessors);

    // Finally, re-register all internal BeanPostProcessors.
    // 将所有实现了MergedBeanDefinitionPostProcessor类型的BeanPostProcessor进行排序操作
    sortPostProcessors(internalPostProcessors, beanFactory);
    // 注册所有实现了MergedBeanDefinitionPostProcessor类型的BeanPostProcessor到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).
    // 注册ApplicationListenerDetector到beanFactory中
    beanFactory.addBeanPostProcessor(new ApplicationListenerDetector(applicationContext));
}

BeanPostProcessor 主要接口有两个方法:

image.png

初始化方法调用前要进行的处理逻辑
@Nullable
default Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
   return bean;
}

初始化方法调用后要进行的处理逻辑
@Nullable
default Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
   return bean;
}

在registerBeanPostProcessors方法中手动添加了一个 BeanPostProcessor,BeanPostProcessorChecker的作用主要用于记录信息

// 添加BeanPostProcessorChecker(主要用于记录信息)到beanFactory中 
beanFactory.addBeanPostProcessor(new BeanPostProcessorChecker(beanFactory, beanProcessorTargetCount));

我们可以看一下BeanPostProcessorChecker的postProcessAfterInitialization方法,主要就是记录了一下日志信息:

/**
 * 后置处理器的after方法,用来判断哪些是不需要检测的bean
 * @param bean the new bean instance
 * @param beanName the name of the bean
 * @return
 */
@Override
public Object postProcessAfterInitialization(Object bean, String beanName) {
    // 如果bean不是BeanPostProcessor实例 && beanName 不是 完全内部使用 && beanFactory当前注册的BeanPostProcessor
    // 数量小于 BeanPostProcessor目标数量
    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)");
        }
    }
    // 返回bean
    return bean;
}

其中有一个 isInfrastructureBean 方法的判断,是用来判断 beanName 是否是完全内部使用,在 BeanDefinition中定义了bean的角色类型:

/**
 * 用户自定义bean的角色类型
 *
 * Role hint indicating that a {@code BeanDefinition} is a major part
 * of the application. Typically corresponds to a user-defined bean.
 */
int ROLE_APPLICATION = 0;

/**
 * 某些复杂的配置类
 *
 * Role hint indicating that a {@code BeanDefinition} is a supporting
 * part of some larger configuration, typically an outer
 * {@link org.springframework.beans.factory.parsing.ComponentDefinition}.
 * {@code SUPPORT} beans are considered important enough to be aware
 * of when looking more closely at a particular
 * {@link org.springframework.beans.factory.parsing.ComponentDefinition},
 * but not when looking at the overall configuration of an application.
 */
int ROLE_SUPPORT = 1;

/**
 * spring内部使用的bean角色
 *
 * Role hint indicating that a {@code BeanDefinition} is providing an
 * entirely background role and has no relevance to the end-user. This hint is
 * used when registering beans that are completely part of the internal workings
 * of a {@link org.springframework.beans.factory.parsing.ComponentDefinition}.
 */
int ROLE_INFRASTRUCTURE = 2;

看看 BeanPostProcessor 的比较关键的几个子接口: image.png

  • DestructionAwareBeanPostProcessor image.png postProcessBeforeDestruction在bean被销毁前调用,在BeanFactory的注解中,说明bean的生命周期的时候有提到:
* <p>On shutdown of a bean factory, the following lifecycle methods apply:
* <ol>
* <li>{@code postProcessBeforeDestruction} methods of DestructionAwareBeanPostProcessors
* <li>DisposableBean's {@code destroy}
* <li>a custom destroy-method definition
  • MergedBeanDefinitionPostProcessor
/**
 *spring通过此方法找出所有需要注入的字段,同时做缓存
 *
 * Post-process the given merged bean definition for the specified bean.
 * @param beanDefinition the merged bean definition for the bean
 * @param beanType the actual type of the managed bean instance
 * @param beanName the name of the bean
 * @see AbstractAutowireCapableBeanFactory#applyMergedBeanDefinitionPostProcessors
 */
void postProcessMergedBeanDefinition(RootBeanDefinition beanDefinition, Class<?> beanType, String beanName);
  • SmartInstantiationAwareBeanPostProcessor
/**
 * 预测bean的类型,主要是在bean还没有创建前我们需要获取bean的类型
 *
 * Predict the type of the bean to be eventually returned from this
 * processor's {@link #postProcessBeforeInstantiation} callback.
 * <p>The default implementation returns {@code null}.
 * @param beanClass the raw class of the bean
 * @param beanName the name of the bean
 * @return the type of the bean, or {@code null} if not predictable
 * @throws org.springframework.beans.BeansException in case of errors
 */
@Nullable
default Class<?> predictBeanType(Class<?> beanClass, String beanName) throws BeansException {
   return null;
}

/**
 * 完成对构造函数的解析和推断
 *
 * Determine the candidate constructors to use for the given bean.
 * <p>The default implementation returns {@code null}.
 * @param beanClass the raw class of the bean (never {@code null})
 * @param beanName the name of the bean
 * @return the candidate constructors, or {@code null} if none specified
 * @throws org.springframework.beans.BeansException in case of errors
 */
@Nullable
default Constructor<?>[] determineCandidateConstructors(Class<?> beanClass, String beanName)
      throws BeansException {

   return null;
}

/**
 * 解决循环依赖问题,通过此方法提前暴露一个合格的对象
 *
 * Obtain a reference for early access to the specified bean,
 * typically for the purpose of resolving a circular reference.
 * <p>This callback gives post-processors a chance to expose a wrapper
 * early - that is, before the target bean instance is fully initialized.
 * The exposed object should be equivalent to the what
 * {@link #postProcessBeforeInitialization} / {@link #postProcessAfterInitialization}
 * would expose otherwise. Note that the object returned by this method will
 * be used as bean reference unless the post-processor returns a different
 * wrapper from said post-process callbacks. In other words: Those post-process
 * callbacks may either eventually expose the same reference or alternatively
 * return the raw bean instance from those subsequent callbacks (if the wrapper
 * for the affected bean has been built for a call to this method already,
 * it will be exposes as final bean reference by default).
 * <p>The default implementation returns the given {@code bean} as-is.
 * @param bean the raw bean instance
 * @param beanName the name of the bean
 * @return the object to expose as bean reference
 * (typically with the passed-in bean instance as default)
 * @throws org.springframework.beans.BeansException in case of errors
 */
default Object getEarlyBeanReference(Object bean, String beanName) throws BeansException {
   return bean;
}

其中的 getEarlyBeanReference 方法就是用来解决循环依赖问题的。