Spring注解--AOP原理(三):BeanPostProcessor创建与注册

1. 用途

Spring 中使用BeanPostProcessor 来拦截bean的创建,并在bean初始化前后,添加相应的操作。

2. 注册流程

  1. 传入配置类,创建IOC容器
  2. 注册配置类,调用refresh,初始化容器
  3. 容器初始化的时候,注册BeanPostProcessor
// Register bean processors that intercept bean creation.
registerBeanPostProcessors(beanFactory);
  • 找到容器中,需要创建的BeanPostProcessors
String[] postProcessorNames = beanFactory.getBeanNamesForType(BeanPostProcessor.class, true, false);

  • 分离不同的BeanPostProcessors(implements PriorityOrdered,Ordered)
List priorityOrderedPostProcessors = new ArrayList();
List internalPostProcessors = new ArrayList();
List orderedPostProcessorNames = new ArrayList();
List nonOrderedPostProcessorNames = new ArrayList();
  • 优先级顺序
    PriorityOrdered > Ordered > 普通的BeanPostProcessor
  • 最后创建并注册BeanPostProcessor到beanFactory中
List nonOrderedPostProcessors = new ArrayList();
for (String ppName : nonOrderedPostProcessorNames) {
    BeanPostProcessor pp = beanFactory.getBean(ppName,BeanPostProcessor.class);
    nonOrderedPostProcessors.add(pp);
    if (pp instanceof MergedBeanDefinitionPostProcessor) {              
        internalPostProcessors.add(pp);       
    }
}
registerBeanPostProcessors(beanFactory, nonOrderedPostProcessors);
private static void registerBeanPostProcessors(
            ConfigurableListableBeanFactory beanFactory, List postProcessors) {
        for (BeanPostProcessor postProcessor : postProcessors) {
            beanFactory.addBeanPostProcessor(postProcessor);
        }
    }

3. 创建流程

  • 创建BeanPostProcessors实例的流程和创建一般bean实例一样(具体debug过程不详细描述)(AbstractAutowireCapableBeanFactory)
protected Object doCreateBean(final String beanName, final RootBeanDefinition mbd, final Object[] args) {
    //创建bean实例
    instanceWrapper = createBeanInstance(beanName, mbd, args);
    ...
    //给bean的属性赋值
    populateBean(beanName, mbd, instanceWrapper);
    //初始化bean
    if (exposedObject != null) {
        exposedObject = initializeBean(beanName, exposedObject, mbd);
    }
    ...
}
  • bean初始化
protected Object initializeBean(final String beanName, final Object bean, RootBeanDefinition mbd) {
  //处理Aware接口的方法回调
  invokeAwareMethods(beanName, bean);
  ...
  //调用PostBeanProcessor的postProcessBeforeInitialization
  wrappedBean = applyBeanPostProcessorsBeforeInitialization(wrappedBean, beanName)
  ...
  //执行自定义的初始方法(implements InitializingBean)
  invokeInitMethods(beanName, wrappedBean, mbd);
  ...
  //最后调用PostBeanProcessor的postProcessAfterInitialization
  wrappedBean = applyBeanPostProcessorsAfterInitialization(wrappedBean, beanName)
}

你可能感兴趣的:(Spring注解--AOP原理(三):BeanPostProcessor创建与注册)