Spring扩展功能BeanFactoryPostProcessor源码解读

前面我们通过简单的案例学习了BeanFactoryPostProcessor,同样也知道了BeanFactoryPostProcessor的作用,那么本篇就来深入的学习下其相关源码的知识,首先我们分析的入口是我们的IOC容器的创建,即【AnnotationConfigApplicationContext】,代码如下:

 @Test
public void testExpand(){
    AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext(ExpandConfig.class);
    applicationContext.close();
}

首先Dbug进来来到#方法AnnotationConfigApplicationContext(Class... componentClasses),具体代码片段如下:

  public AnnotationConfigApplicationContext(Class... componentClasses) {
    this();
    this.register(componentClasses);
    this.refresh();
}

上述方法this.refresh()是我们Ioc容器创建核心代码进去来到:

  • 其中有一步直接调用我们的beanFactoryPostProcessor,代码片段如下:
  this.invokeBeanFactoryPostProcessors(beanFactory);

Dbug进去来到AbstractApplicationContext#invokeBeanFactoryPostProcessors(ConfigurableListableBeanFactory beanFactory)方法

protected void invokeBeanFactoryPostProcessors(ConfigurableListableBeanFactory beanFactory) {
    PostProcessorRegistrationDelegate.invokeBeanFactoryPostProcessors(beanFactory, this.getBeanFactoryPostProcessors());
    if (beanFactory.getTempClassLoader() == null && beanFactory.containsBean("loadTimeWeaver")) {
        beanFactory.addBeanPostProcessor(new LoadTimeWeaverAwareProcessor(beanFactory));
        beanFactory.setTempClassLoader(new ContextTypeMatchClassLoader(beanFactory.getBeanClassLoader()));
    }

}

所有的方法操作都在PostProcessorRegistrationDelegate#invokeBeanFactoryPostProcessors(...)中完成,继续跟踪代码来到:

  • 方法主要的作用是在beanFactory中找所有类型为BeanFactoryPostProcessor的组件,并执行其方法
postProcessor.postProcessBeanFactory(beanFactory);

当然在执行方法时是在其他组件创建和初始化之前来调用的,其实这就是BeanFactoryPostProcessor【后置处理器】的源码分析,代码太长,感兴趣的可以自己Dbug一步一步看下是如何找到其组件的过程。

你可能感兴趣的:(Spring扩展功能BeanFactoryPostProcessor源码解读)