Spring源码分析之BeanPostProcessor接口和BeanFactoryPostProcessor接口方法不执行原因分析

过程分析的很精彩,原文转载:https://blog.csdn.net/u011734144/article/details/72600932

首先下面是我的Bean

[html]   view plain  copy
  1. /*  
  2.  * Copyright 2002-2017 the original author or authors.  
  3.  *  
  4.  * Licensed under the Apache License, Version 2.0 (the "License");  
  5.  * you may not use this file except in compliance with the License.  
  6.  * You may obtain a copy of the License at  
  7.  *  
  8.  *      http://www.apache.org/licenses/LICENSE-2.0  
  9.  *  
  10.  * Unless required by applicable law or agreed to in writing, software  
  11.  * distributed under the License is distributed on an "AS IS" BASIS,  
  12.  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.  
  13.  * See the License for the specific language governing permissions and  
  14.  * limitations under the License.  
  15.  */  
  16. package com.verify.constant;  
  17.   
  18. import org.springframework.beans.BeansException;  
  19. import org.springframework.beans.PropertyValues;  
  20. import org.springframework.beans.factory.*;  
  21. import org.springframework.beans.factory.config.BeanFactoryPostProcessor;  
  22. import org.springframework.beans.factory.config.BeanPostProcessor;  
  23. import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;  
  24. import org.springframework.beans.factory.config.InstantiationAwareBeanPostProcessor;  
  25.   
  26. import java.beans.PropertyDescriptor;  
  27.   
  28. /**  
  29.  * TODO  
  30.  *  
  31.  * @author linjiedeng  
  32.  * @date 17/5/8 下午10:47  
  33.  * @since TODO  
  34.  */  
  35. public class StudentService implements BeanPostProcessor, InitializingBean, BeanFactoryPostProcessor, BeanNameAware, BeanClassLoaderAware, BeanFactoryAware {  
  36.   
  37.     private ClassLoader classLoader;  
  38.   
  39.     private BeanFactory beanFactory;  
  40.   
  41.     private String name;  
  42.   
  43.     @Override  
  44.     public void setBeanClassLoader(ClassLoader classLoader) {  
  45.         this.classLoader = classLoader; //实现BeanClassLoaderAware接口可以获取到对应的classLoader  
  46.         System.out.println("set bean class loader");  
  47.         System.out.println(classLoader);  
  48.     }  
  49.   
  50.     @Override  
  51.     public void setBeanFactory(BeanFactory beanFactory) throws BeansException {  
  52.         this.beanFactory = beanFactory; //实现BeanFactoryAware接口获取该Bean的beanFactory  
  53.         System.out.println("set bean factory");  
  54.         System.out.println(beanFactory);  
  55.     }  
  56.   
  57.     @Override  
  58.     public void setBeanName(String name) {  
  59.         this.name = name;   //实现BeanNameAware接口获取该Bean的名字  
  60.         System.out.println("set bean name");  
  61.         System.out.println(name);  
  62.     }  
  63.   
  64.     public void initMethod() {  
  65.         System.out.println("init method");  
  66.     }  
  67.   
  68.     @Override  
  69.     public void afterPropertiesSet() throws Exception {  
  70.         System.out.println("afterPropertiesSet");  
  71.     }  
  72.   
  73.     @Override  
  74.     public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {  
  75.         System.out.println("postProcessBeforeInitialization");  
  76.         return bean;  
  77.     }  
  78.   
  79.     @Override  
  80.     public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {  
  81.         System.out.println("postProcessAfterInitialization");  
  82.         return bean;  
  83.     }  
  84.   
  85.     @Override  
  86.     public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {  
  87.         System.out.println("postProcessBeanFactory");  
  88.     }  
  89.   
  90.     public void read() {  
  91.         System.out.println("Student service read");  
  92.     }  
  93.   
  94. }  


bean的配置文件applicationContext.xml内容如下:

[html]   view plain  copy
  1. <?xml version="1.0" encoding="UTF-8"?>  
  2. <beans xmlns="http://www.springframework.org/schema/beans"  
  3.        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  
  4.        xmlns:context="http://www.springframework.org/schema/context"  
  5.        xsi:schemaLocation="http://www.springframework.org/schema/beans  
  6.         http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">  
  7.   
  8.     <bean id="studentService" class="com.verify.constant.StudentService" init-method="initMethod"/>  
  9. </beans>  


测试代码如下:

[html]   view plain  copy
  1. @Test  
  2.     public void test2() {  
  3.         ClassPathResource resource = new ClassPathResource("applicationContext.xml");  
  4.         DefaultListableBeanFactory factory = new DefaultListableBeanFactory();  
  5.         XmlBeanDefinitionReader reader = new XmlBeanDefinitionReader(factory);  
  6.         reader.loadBeanDefinitions(resource);  
  7.         StudentService studentService = (StudentService)factory.getBean("studentService");  
  8.         studentService.read();  
  9.     }  

测试代码执行后,其他方法都执行了,但是唯独BeanPostProcessor接口的两个方法postProcessBeforeInitialization和postProcessAfterInitialization以及

BeanFactoryPostProcessor接口的方法没有执行,这我就有点疑惑了,这是咋回事?其实这两个接口应该是在bean初始化的过程中被调用,是在AbstractAutowireCapableBeanFactory接口的initializeBean初始化方法中被调用的,代码如下:

[html]   view plain  copy
  1. protected Object initializeBean(final String beanName, final Object bean, RootBeanDefinition mbd) {  
  2.         if (System.getSecurityManager() != null) {  
  3.             AccessController.doPrivileged(new PrivilegedAction<Object>() {  
  4.                 @Override  
  5.                 public Object run() {  
  6.                     invokeAwareMethods(beanName, bean);  
  7.                     return null;  
  8.                 }  
  9.             }, getAccessControlContext());  
  10.         }  
  11.         else {  
  12.             invokeAwareMethods(beanName, bean);  
  13.         }  
  14.   
  15.         Object wrappedBean = bean;  
  16.         if (mbd == null || !mbd.isSynthetic()) {  
  17.             //执行BeanPostProcessor扩展点的PostProcessBeforeInitialization进行修改实例化Bean  
  18.             wrappedBean = applyBeanPostProcessorsBeforeInitialization(wrappedBean, beanName);  
  19.         }  
  20.   
  21.         try {  
  22.             //调用Bean的初始化方法,这个初始化方法是在BeanDefinition中通过定义init-method属性指定的  
  23.             //同时,如果Bean实现了InitializingBean接口,那么这个Bean的afterPropertiesSet实现也不会被调用  
  24.             invokeInitMethods(beanName, wrappedBean, mbd);  
  25.         }  
  26.         catch (Throwable ex) {  
  27.             throw new BeanCreationException(  
  28.                     (mbd != null ? mbd.getResourceDescription() : null),  
  29.                     beanName, "Invocation of init method failed", ex);  
  30.         }  
  31.   
  32.         if (mbd == null || !mbd.isSynthetic()) {  
  33.             //执行BeanPostProcessor扩展点的PostProcessAfterInitialization进行修改实例化Bean  
  34.             wrappedBean = applyBeanPostProcessorsAfterInitialization(wrappedBean, beanName);  
  35.         }  
  36.         return wrappedBean;  
  37.     }  

initializeBean方法是Bean的初始化方法,在该初始化方法中会调用Bean的一些初始化方法,比如如下方法:

[html]   view plain  copy
  1. private void invokeAwareMethods(final String beanName, final Object bean) {  
  2.         if (bean instanceof Aware) {  
  3.             if (bean instanceof BeanNameAware) {  
  4.                 ((BeanNameAware) bean).setBeanName(beanName);  
  5.             }  
  6.             if (bean instanceof BeanClassLoaderAware) {  
  7.                 ((BeanClassLoaderAware) bean).setBeanClassLoader(getBeanClassLoader());  
  8.             }  
  9.             if (bean instanceof BeanFactoryAware) {  
  10.                 ((BeanFactoryAware) bean).setBeanFactory(AbstractAutowireCapableBeanFactory.this);  
  11.             }  
  12.         }  
  13.     }  

即只要Bean实现了BeanNameAware接口,这里就会帮你调用,BeanClassLoaderAware和BeanFactory接口同样如此,上述我的代码中就实现了这三个接口,启动的过程中都被调用了,再实现的方法中可以获取这些信息,并存储。

再比如如下方法:

[html]   view plain  copy
  1. public Object applyBeanPostProcessorsBeforeInitialization(Object existingBean, String beanName)  
  2.             throws BeansException {  
  3.   
  4.         Object result = existingBean;  
  5.         for (BeanPostProcessor beanProcessor : getBeanPostProcessors()) {  
  6.             result = beanProcessor.postProcessBeforeInitialization(result, beanName);  
  7.             if (result == null) {  
  8.                 return result;  
  9.             }  
  10.         }  
  11.         return result;  
  12.     }  

这里其实是如果Bean实现了BeanPostProcessor接口,这里就会调用bean实现的 postProcessBeforeInitialization方法,这是在bean的真正初始化之前被调用

对应的BeanPostProcessor接口的另外一个方法,是在bean的初始化之后被调用,如下:

[html]   view plain  copy
  1. public Object applyBeanPostProcessorsAfterInitialization(Object existingBean, String beanName)  
  2.             throws BeansException {  
  3.   
  4.         Object result = existingBean;  
  5.         for (BeanPostProcessor beanProcessor : getBeanPostProcessors()) {  
  6.             result = beanProcessor.postProcessAfterInitialization(result, beanName);  
  7.             if (result == null) {  
  8.                 return result;  
  9.             }  
  10.         }  
  11.         return result;  
  12.     }  

真正的初始化是在如下方法:

[html]   view plain  copy
  1. protected void invokeInitMethods(String beanName, final Object bean, RootBeanDefinition mbd)  
  2.             throws Throwable {  
  3.   
  4.         boolean isInitializingBean = (bean instanceof InitializingBean);  
  5.         if (isInitializingBean && (mbd == null || !mbd.isExternallyManagedInitMethod("afterPropertiesSet"))) {  
  6.             if (logger.isDebugEnabled()) {  
  7.                 logger.debug("Invoking afterPropertiesSet() on bean with name '" + beanName + "'");  
  8.             }  
  9.             if (System.getSecurityManager() != null) {  
  10.                 try {  
  11.                     AccessController.doPrivileged(new PrivilegedExceptionAction<Object>() {  
  12.                         @Override  
  13.                         public Object run() throws Exception {  
  14.                             ((InitializingBean) bean).afterPropertiesSet();  
  15.                             return null;  
  16.                         }  
  17.                     }, getAccessControlContext());  
  18.                 }  
  19.                 catch (PrivilegedActionException pae) {  
  20.                     throw pae.getException();  
  21.                 }  
  22.             }  
  23.             else {  
  24.                 ((InitializingBean) bean).afterPropertiesSet(); //启动afterPropertiesSet,afterPropertiesSet是InitializingBean接口的方法  
  25.             }  
  26.         }  
  27.   
  28.         if (mbd != null) {  
  29.             String initMethodName = mbd.getInitMethodName();    //获取用户自定义的初始化方法  
  30.             if (initMethodName != null && !(isInitializingBean && "afterPropertiesSet".equals(initMethodName)) &&  
  31.                     !mbd.isExternallyManagedInitMethod(initMethodName)) {  
  32.                 invokeCustomInitMethod(beanName, bean, mbd);    //调用自定义的初始化方法  
  33.             }  
  34.         }  
  35.     }  

可以看到,上述代码实际上是在调用Bean实现的initializingBean接口的afterPropertiesSet方法来初始化Bean,接下来还调用了用户自定义的init-method方法,可以看到上面我的applicationContext.xml配置文件中配置的有一个initMethod方法,这就是自定义的初始化方法,这个方法也是在这里被调用的


好,代码分析到这,也可以看到了,既然这里初始化的时候调用了BeanPostProcessor的那两个方法,但是我的测试代码为什么没有执行这两个方法呢?

其实可以看到真正执行BeanPostProcessor接口的代码是如下代码:

 
[html]   view plain  copy
  1. public Object applyBeanPostProcessorsBeforeInitialization(Object existingBean, String beanName)  
  2.             throws BeansException {  
  3.   
  4.         Object result = existingBean;  
  5.         for (BeanPostProcessor beanProcessor : getBeanPostProcessors()) {  
  6.             result = beanProcessor.postProcessBeforeInitialization(result, beanName);  
  7.             if (result == null) {  
  8.                 return result;  
  9.             }  
  10.         }  
  11.         return result;  
  12.     }  

其中的getBeanPostProcessors()方法获取的实际就是AbstractBeanFactory的this . beanPostProcessors属性值,看来是这个属性值为空,所以执行的时候没有调用
那接下来要分析的原因就是为什么this.beanPostProcessors属性值为空呢?或者说bean的载入时为什么没有载入进来呢?那就要看它是在哪里载入的了,最终定位到载入是在
AbstractApplicationContext中执行的
[html]   view plain  copy
  1. @Override  
  2.     public void refresh() throws BeansException, IllegalStateException {  
  3.         synchronized (this.startupShutdownMonitor) {  
  4.             // Prepare this context for refreshing.  
  5.             prepareRefresh();  
  6.   
  7.             //这是在子类中启动refreshBeanFactory的地方  
  8.             // Tell the subclass to refresh the internal bean factory.  
  9.             ConfigurableListableBeanFactory beanFactory = obtainFreshBeanFactory();  
  10.   
  11.             // Prepare the bean factory for use in this context.  
  12.             prepareBeanFactory(beanFactory);  
  13.   
  14.             try {  
  15.                 // Allows post-processing of the bean factory in context subclasses.  
  16.                 // 设置BeanFactory的后置处理  
  17.                 postProcessBeanFactory(beanFactory);  
  18.   
  19.                 // Invoke factory processors registered as beans in the context.  
  20.                 // 调用BeanFactory的后处理器,这些后处理器是在Bean定义中向容器注册的  
  21.                 invokeBeanFactoryPostProcessors(beanFactory);  
  22.   
  23.                 // Register bean processors that intercept bean creation.  
  24.                 // 注册Bean的后处理器,在Bean创建过程中调用  
  25.                 registerBeanPostProcessors(beanFactory);  
  26.   
  27.                 // Initialize message source for this context.  
  28.                 // 对上下文中的消息源进行初始化  
  29.                 initMessageSource();  
  30.   
  31.                 // Initialize event multicaster for this context.  
  32.                 // 初始化上下文中的事件机制  
  33.                 initApplicationEventMulticaster();  
  34.   
  35.                 // Initialize other special beans in specific context subclasses.  
  36.                 // 初始化其他的特殊Bean  
  37.                 onRefresh();  
  38.   
  39.                 // Check for listener beans and register them.  
  40.                 // 检查监听Bean,并且将这些Bean向容器注册  
  41.                 registerListeners();  
  42.   
  43.                 // Instantiate all remaining (non-lazy-init) singletons.这里是对lazy-init属性进行处理的地方  
  44.                 finishBeanFactoryInitialization(beanFactory);  
  45.   
  46.                 // Last step: publish corresponding event.  
  47.                 // 发布容器事件,结束Refresh过程  
  48.                 finishRefresh();  
  49.             }  
  50.   
  51.             catch (BeansException ex) {  
  52.                 if (logger.isWarnEnabled()) {  
  53.                     logger.warn("Exception encountered during context initialization - " +  
  54.                             "cancelling refresh attempt: " + ex);  
  55.                 }  
  56.   
  57.                 // Destroy already created singletons to avoid dangling resources.  
  58.                 // 为防止Bean资环占用,在异常处理中,销毁已经在前面过程中生成的单件Bean  
  59.                 destroyBeans();  
  60.   
  61.                 // Reset 'active' flag.  
  62.                 cancelRefresh(ex);  
  63.   
  64.                 // Propagate exception to caller.  
  65.                 throw ex;  
  66.             }  
  67.   
  68.             finally {  
  69.                 // Reset common introspection caches in Spring's core, since we  
  70.                 // might not ever need metadata for singleton beans anymore...  
  71.                 resetCommonCaches();  
  72.             }  
  73.         }  
  74.     }  


registerBeanPostProcessors(beanFactory)是载入Bean实现的BeanPostProcessor接口,具体载入代码如下:
 
[html]   view plain  copy
  1. public static void registerBeanPostProcessors(  
  2.             ConfigurableListableBeanFactory beanFactory, AbstractApplicationContext applicationContext) {  
  3.   
  4.         String[] postProcessorNames = beanFactory.getBeanNamesForType(BeanPostProcessor.class, true, false);  
  5.   
  6.         // Register BeanPostProcessorChecker that logs an info message when  
  7.         // a bean is created during BeanPostProcessor instantiation, i.e. when  
  8.         // a bean is not eligible for getting processed by all BeanPostProcessors.  
  9.         int beanProcessorTargetCount = beanFactory.getBeanPostProcessorCount() + 1 + postProcessorNames.length;  
  10.         beanFactory.addBeanPostProcessor(new BeanPostProcessorChecker(beanFactory, beanProcessorTargetCount));  
  11.   
  12.         // Separate between BeanPostProcessors that implement PriorityOrdered,  
  13.         // Ordered, and the rest.  
  14.         List<BeanPostProcessor> priorityOrderedPostProcessors = new ArrayList<>();  
  15.         List<BeanPostProcessor> internalPostProcessors = new ArrayList<>();  
  16.         List<String> orderedPostProcessorNames = new ArrayList<>();  
  17.         List<String> nonOrderedPostProcessorNames = new ArrayList<>();  
  18.         for (String ppName : postProcessorNames) {  
  19.             if (beanFactory.isTypeMatch(ppName, PriorityOrdered.class)) {  
  20.                 BeanPostProcessor pp = beanFactory.getBean(ppName, BeanPostProcessor.class);  
  21.                 priorityOrderedPostProcessors.add(pp);  
  22.                 if (pp instanceof MergedBeanDefinitionPostProcessor) {  
  23.                     internalPostProcessors.add(pp);  
  24.                 }  
  25.             }  
  26.             else if (beanFactory.isTypeMatch(ppName, Ordered.class)) {  
  27.                 orderedPostProcessorNames.add(ppName);  
  28.             }  
  29.             else {  
  30.                 nonOrderedPostProcessorNames.add(ppName);  
  31.             }  
  32.         }  
  33.   
  34.         // First, register the BeanPostProcessors that implement PriorityOrdered.  
  35.         sortPostProcessors(beanFactory, priorityOrderedPostProcessors);  
  36.         registerBeanPostProcessors(beanFactory, priorityOrderedPostProcessors);  
  37.   
  38.         // Next, register the BeanPostProcessors that implement Ordered.  
  39.         List<BeanPostProcessor> orderedPostProcessors = new ArrayList<>();  
  40.         for (String ppName : orderedPostProcessorNames) {  
  41.             BeanPostProcessor pp = beanFactory.getBean(ppName, BeanPostProcessor.class);  
  42.             orderedPostProcessors.add(pp);  
  43.             if (pp instanceof MergedBeanDefinitionPostProcessor) {  
  44.                 internalPostProcessors.add(pp);  
  45.             }  
  46.         }  
  47.         sortPostProcessors(beanFactory, orderedPostProcessors);  
  48.         registerBeanPostProcessors(beanFactory, orderedPostProcessors);  
  49.   
  50.         // Now, register all regular BeanPostProcessors.  
  51.         List<BeanPostProcessor> nonOrderedPostProcessors = new ArrayList<>();  
  52.         for (String ppName : nonOrderedPostProcessorNames) {  
  53.             BeanPostProcessor pp = beanFactory.getBean(ppName, BeanPostProcessor.class);  
  54.             nonOrderedPostProcessors.add(pp);  
  55.             if (pp instanceof MergedBeanDefinitionPostProcessor) {  
  56.                 internalPostProcessors.add(pp);  
  57.             }  
  58.         }  
  59.         registerBeanPostProcessors(beanFactory, nonOrderedPostProcessors);  
  60.   
  61.         // Finally, re-register all internal BeanPostProcessors.  
  62.         sortPostProcessors(beanFactory, internalPostProcessors);  
  63.         registerBeanPostProcessors(beanFactory, internalPostProcessors);  
  64.   
  65.         beanFactory.addBeanPostProcessor(new ApplicationListenerDetector(applicationContext));  
  66.     }  
invokeBeanFactoryPostProcessors(beanFactory)是载入Bean实现的BeanFactoryPostProcessor接口,具体载入如下:
 
[html]   view plain  copy
  1. public static void invokeBeanFactoryPostProcessors(  
  2.             ConfigurableListableBeanFactory beanFactory, List<BeanFactoryPostProcessor> beanFactoryPostProcessors) {  
  3.   
  4.         // Invoke BeanDefinitionRegistryPostProcessors first, if any.  
  5.         Set<String> processedBeans = new HashSet<>();  
  6.   
  7.         if (beanFactory instanceof BeanDefinitionRegistry) {  
  8.             BeanDefinitionRegistry registry = (BeanDefinitionRegistry) beanFactory;  
  9.             List<BeanFactoryPostProcessor> regularPostProcessors = new LinkedList<>();  
  10.             List<BeanDefinitionRegistryPostProcessor> registryPostProcessors =  
  11.                     new LinkedList<>();  
  12.   
  13.             for (BeanFactoryPostProcessor postProcessor : beanFactoryPostProcessors) {  
  14.                 if (postProcessor instanceof BeanDefinitionRegistryPostProcessor) {  
  15.                     BeanDefinitionRegistryPostProcessor registryPostProcessor =  
  16.                             (BeanDefinitionRegistryPostProcessor) postProcessor;  
  17.                     registryPostProcessor.postProcessBeanDefinitionRegistry(registry);  
  18.                     registryPostProcessors.add(registryPostProcessor);  
  19.                 }  
  20.                 else {  
  21.                     regularPostProcessors.add(postProcessor);  
  22.                 }  
  23.             }  
  24.   
  25.             // Do not initialize FactoryBeans here: We need to leave all regular beans  
  26.             // uninitialized to let the bean factory post-processors apply to them!  
  27.             // Separate between BeanDefinitionRegistryPostProcessors that implement  
  28.             // PriorityOrdered, Ordered, and the rest.  
  29.             String[] postProcessorNames =  
  30.                     beanFactory.getBeanNamesForType(BeanDefinitionRegistryPostProcessor.class, true, false);  
  31.   
  32.             // First, invoke the BeanDefinitionRegistryPostProcessors that implement PriorityOrdered.  
  33.             List<BeanDefinitionRegistryPostProcessor> priorityOrderedPostProcessors = new ArrayList<>();  
  34.             for (String ppName : postProcessorNames) {  
  35.                 if (beanFactory.isTypeMatch(ppName, PriorityOrdered.class)) {  
  36.                     priorityOrderedPostProcessors.add(beanFactory.getBean(ppName, BeanDefinitionRegistryPostProcessor.class));  
  37.                     processedBeans.add(ppName);  
  38.                 }  
  39.             }  
  40.             sortPostProcessors(beanFactory, priorityOrderedPostProcessors);  
  41.             registryPostProcessors.addAll(priorityOrderedPostProcessors);  
  42.             invokeBeanDefinitionRegistryPostProcessors(priorityOrderedPostProcessors, registry);  
  43.   
  44.             // Next, invoke the BeanDefinitionRegistryPostProcessors that implement Ordered.  
  45.             postProcessorNames = beanFactory.getBeanNamesForType(BeanDefinitionRegistryPostProcessor.class, true, false);  
  46.             List<BeanDefinitionRegistryPostProcessor> orderedPostProcessors = new ArrayList<>();  
  47.             for (String ppName : postProcessorNames) {  
  48.                 if (!processedBeans.contains(ppName) && beanFactory.isTypeMatch(ppName, Ordered.class)) {  
  49.                     orderedPostProcessors.add(beanFactory.getBean(ppName, BeanDefinitionRegistryPostProcessor.class));  
  50.                     processedBeans.add(ppName);  
  51.                 }  
  52.             }  
  53.             sortPostProcessors(beanFactory, orderedPostProcessors);  
  54.             registryPostProcessors.addAll(orderedPostProcessors);  
  55.             invokeBeanDefinitionRegistryPostProcessors(orderedPostProcessors, registry);  
  56.   
  57.             // Finally, invoke all other BeanDefinitionRegistryPostProcessors until no further ones appear.  
  58.             boolean reiterate = true;  
  59.             while (reiterate) {  
  60.                 reiterate = false;  
  61.                 postProcessorNames = beanFactory.getBeanNamesForType(BeanDefinitionRegistryPostProcessor.class, true, false);  
  62.                 for (String ppName : postProcessorNames) {  
  63.                     if (!processedBeans.contains(ppName)) {  
  64.                         BeanDefinitionRegistryPostProcessor pp = beanFactory.getBean(ppName, BeanDefinitionRegistryPostProcessor.class);  
  65.                         registryPostProcessors.add(pp);  
  66.                         processedBeans.add(ppName);  
  67.                         pp.postProcessBeanDefinitionRegistry(registry);  
  68.                         reiterate = true;  
  69.                     }  
  70.                 }  
  71.             }  
  72.   
  73.             // Now, invoke the postProcessBeanFactory callback of all processors handled so far.  
  74.             invokeBeanFactoryPostProcessors(registryPostProcessors, beanFactory);  
  75.             invokeBeanFactoryPostProcessors(regularPostProcessors, beanFactory);  
  76.         }  
  77.   
  78.         else {  
  79.             // Invoke factory processors registered with the context instance.  
  80.             invokeBeanFactoryPostProcessors(beanFactoryPostProcessors, beanFactory);  
  81.         }  
  82.   
  83.         // Do not initialize FactoryBeans here: We need to leave all regular beans  
  84.         // uninitialized to let the bean factory post-processors apply to them!  
  85.         String[] postProcessorNames =  
  86.                 beanFactory.getBeanNamesForType(BeanFactoryPostProcessor.class, true, false);  
  87.   
  88.         // Separate between BeanFactoryPostProcessors that implement PriorityOrdered,  
  89.         // Ordered, and the rest.  
  90.         List<BeanFactoryPostProcessor> priorityOrderedPostProcessors = new ArrayList<>();  
  91.         List<String> orderedPostProcessorNames = new ArrayList<>();  
  92.         List<String> nonOrderedPostProcessorNames = new ArrayList<>();  
  93.         for (String ppName : postProcessorNames) {  
  94.             if (processedBeans.contains(ppName)) {  
  95.                 // skip - already processed in first phase above  
  96.             }  
  97.             else if (beanFactory.isTypeMatch(ppName, PriorityOrdered.class)) {  
  98.                 priorityOrderedPostProcessors.add(beanFactory.getBean(ppName, BeanFactoryPostProcessor.class));  
  99.             }  
  100.             else if (beanFactory.isTypeMatch(ppName, Ordered.class)) {  
  101.                 orderedPostProcessorNames.add(ppName);  
  102.             }  
  103.             else {  
  104.                 nonOrderedPostProcessorNames.add(ppName);  
  105.             }  
  106.         }  
  107.   
  108.         // First, invoke the BeanFactoryPostProcessors that implement PriorityOrdered.  
  109.         sortPostProcessors(beanFactory, priorityOrderedPostProcessors);  
  110.         invokeBeanFactoryPostProcessors(priorityOrderedPostProcessors, beanFactory);  
  111.   
  112.         // Next, invoke the BeanFactoryPostProcessors that implement Ordered.  
  113.         List<BeanFactoryPostProcessor> orderedPostProcessors = new ArrayList<>();  
  114.         for (String postProcessorName : orderedPostProcessorNames) {  
  115.             orderedPostProcessors.add(beanFactory.getBean(postProcessorName, BeanFactoryPostProcessor.class));  
  116.         }  
  117.         sortPostProcessors(beanFactory, orderedPostProcessors);  
  118.         invokeBeanFactoryPostProcessors(orderedPostProcessors, beanFactory);  
  119.   
  120.         // Finally, invoke all other BeanFactoryPostProcessors.  
  121.         List<BeanFactoryPostProcessor> nonOrderedPostProcessors = new ArrayList<>();  
  122.         for (String postProcessorName : nonOrderedPostProcessorNames) {  
  123.             nonOrderedPostProcessors.add(beanFactory.getBean(postProcessorName, BeanFactoryPostProcessor.class));  
  124.         }  
  125.         invokeBeanFactoryPostProcessors(nonOrderedPostProcessors, beanFactory);  
  126.   
  127.         // Clear cached merged bean definitions since the post-processors might have  
  128.         // modified the original metadata, e.g. replacing placeholders in values...  
  129.         beanFactory.clearMetadataCache();  
  130.     }  

所以我们可以看到BeanPostProcessor接口和BeanFactoryPostProcessor接口的载入只在abstractApplicationContext中执行了,而在DefaultListableBeanFactory
中没有执行,而我们测试用的工厂就是DefaultListableBeanFactory,所以实际是根本没有载入上面两个接口。
接下来我把测试代码换成如下:
 
[html]   view plain  copy
  1. @Test  
  2.     public void test3() {  
  3.         ApplicationContext applicationContext = new ClassPathXmlApplicationContext("applicationContext.xml");  
  4.         StudentService studentService = (StudentService)applicationContext.getBean("studentService");  
  5.         studentService.read();  
  6.     }  

然后执行,可以很清楚的看到那两个接口的方法都执行了。
原因是:ClassPathXmlApplicationContext是abstractApplicationContext的实现,所以使用这个工厂来管理bean,会载入如上两个接口。
 
总结:
其实我们两个测试代码分别使用了DefaultListableBeanFactory和ClassPathXmlApplicationContext作为Bean工厂,ClassPathXmlApplicationContext底层其实
也是使用的DefaultListableBeanFactory作为Bean工厂,但是ClassPathXmlApplicationContext在DefaultListableBeanFactory的基础上额外载入了
BeanPostProcessor接口和BeanFactoryPostProcessor接口,这个载入是在其父接口AbstractApplicationContext中执行的这就是为什么test2测试代码不执行这两个接口的方法的原因。
此外,对于两个工厂而言,真正的在初始化的过程中调用这些接口的地方都是在底层工厂DefaultListableBeanFactory中,而DefaultListableBeanFactory
实际是调用的父接口AbstractAutowireCapableBeanFactory的initializeBean方法来进行初始化,从而调用那些初始化接口的方法
 
 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值