SpringIOC的理解及源码解读(三)

128 阅读6分钟

坚持! 注:我的排版不是很好,我把内容码完后会统一调整。 image.png 昨天看完了obtainFreshBeanFactory()方法,这个方法最主要的工作就是把xml文件解析成BeanDefination然后注册到一个ConcurrentHashMap中。 还剩下一个getBeanFactory,正如其名,就是获取BeanFactory。 image.png image.png 然而这个值不会是空值吧? nonono image.png 我上一篇文章通篇都是给BeanFactory打工的,这下明白了吧。 刚才又看了看源码,忽略了一个小细节。 在loadBeanDefinitions中有这个类的构造方法 image.png 这个XmlBeanDefinitionReader是用ThreadLocal保证并发的 ,哈哈哈。
好了好了。 今天继续往下看prepareBenFactory。
第五行
prepareBeanFactory(beanFactory);,把刚才的beanFactory丢进去,也不知道要干嘛,我们点进去看看。

protected void prepareBeanFactory(ConfigurableListableBeanFactory beanFactory) {
   // Tell the internal bean factory to use the context's class loader etc.
   beanFactory.setBeanClassLoader(getClassLoader());
   if (!shouldIgnoreSpel) {
      beanFactory.setBeanExpressionResolver(new StandardBeanExpressionResolver(beanFactory.getBeanClassLoader()));
   }
   beanFactory.addPropertyEditorRegistrar(new ResourceEditorRegistrar(this, getEnvironment()));

   // Configure the bean factory with context callbacks.
   beanFactory.addBeanPostProcessor(new ApplicationContextAwareProcessor(this));
   beanFactory.ignoreDependencyInterface(EnvironmentAware.class);
   beanFactory.ignoreDependencyInterface(EmbeddedValueResolverAware.class);
   beanFactory.ignoreDependencyInterface(ResourceLoaderAware.class);
   beanFactory.ignoreDependencyInterface(ApplicationEventPublisherAware.class);
   beanFactory.ignoreDependencyInterface(MessageSourceAware.class);
   beanFactory.ignoreDependencyInterface(ApplicationContextAware.class);
   beanFactory.ignoreDependencyInterface(ApplicationStartupAware.class);

   // BeanFactory interface not registered as resolvable type in a plain factory.
   // MessageSource registered (and found for autowiring) as a bean.
   beanFactory.registerResolvableDependency(BeanFactory.class, beanFactory);
   beanFactory.registerResolvableDependency(ResourceLoader.class, this);
   beanFactory.registerResolvableDependency(ApplicationEventPublisher.class, this);
   beanFactory.registerResolvableDependency(ApplicationContext.class, this);

   // Register early post-processor for detecting inner beans as ApplicationListeners.
   beanFactory.addBeanPostProcessor(new ApplicationListenerDetector(this));

   // Detect a LoadTimeWeaver and prepare for weaving, if found.
   if (!NativeDetector.inNativeImage() && beanFactory.containsBean(LOAD_TIME_WEAVER_BEAN_NAME)) {
      beanFactory.addBeanPostProcessor(new LoadTimeWeaverAwareProcessor(beanFactory));
      // Set a temporary ClassLoader for type matching.
      beanFactory.setTempClassLoader(new ContextTypeMatchClassLoader(beanFactory.getBeanClassLoader()));
   }

   // Register default environment beans.
   if (!beanFactory.containsLocalBean(ENVIRONMENT_BEAN_NAME)) {
      beanFactory.registerSingleton(ENVIRONMENT_BEAN_NAME, getEnvironment());
   }
   if (!beanFactory.containsLocalBean(SYSTEM_PROPERTIES_BEAN_NAME)) {
      beanFactory.registerSingleton(SYSTEM_PROPERTIES_BEAN_NAME, getEnvironment().getSystemProperties());
   }
   if (!beanFactory.containsLocalBean(SYSTEM_ENVIRONMENT_BEAN_NAME)) {
      beanFactory.registerSingleton(SYSTEM_ENVIRONMENT_BEAN_NAME, getEnvironment().getSystemEnvironment());
   }
   if (!beanFactory.containsLocalBean(APPLICATION_STARTUP_BEAN_NAME)) {
      beanFactory.registerSingleton(APPLICATION_STARTUP_BEAN_NAME, getApplicationStartup());
   }
}

好家伙,又是一个BeanFactory的打工仔。 搬来大佬的解释

protected void prepareBeanFactory(ConfigurableListableBeanFactory beanFactory) {
   // 设置为加载当前ApplicationContext类的类加载器   
   beanFactory.setBeanClassLoader(getClassLoader());
   // 设置 BeanExpressionResolver   
   beanFactory.setBeanExpressionResolver(new StandardBeanExpressionResolver(beanFactory.getBeanClassLoader()));
   beanFactory.addPropertyEditorRegistrar(new ResourceEditorRegistrar(this, getEnvironment()));
   // 这里是Spring的又一个扩展点  
   //在所有实现了Aware接口的bean在初始化的时候,这个 processor负责回调,  
   // 这个我们很常用,如我们会为了获取 ApplicationContext 而 implement ApplicationContextAware   
   // 注意:它不仅仅回调 ApplicationContextAware,还会负责回调 EnvironmentAware、ResourceLoaderAware 等   
   beanFactory.addBeanPostProcessor(new ApplicationContextAwareProcessor(this));
   // 下面几行的意思就是,如果某个 bean 依赖于以下几个接口的实现类,在自动装配的时候忽略它们,Spring 会通过其他方式来处理这些依赖。   
   beanFactory.ignoreDependencyInterface(EnvironmentAware.class); 
   beanFactory.ignoreDependencyInterface(EmbeddedValueResolverAware.class); 
   beanFactory.ignoreDependencyInterface(ResourceLoaderAware.class);  
   beanFactory.ignoreDependencyInterface(ApplicationEventPublisherAware.class); 
   beanFactory.ignoreDependencyInterface(MessageSourceAware.class);  
   beanFactory.ignoreDependencyInterface(ApplicationContextAware.class);
   //下面几行就是为特殊的几个 bean 赋值,如果有 bean 依赖了以下几个,会注入这边相应的值  
   beanFactory.registerResolvableDependency(BeanFactory.class, beanFactory);
   beanFactory.registerResolvableDependency(ResourceLoader.class, this);   
   beanFactory.registerResolvableDependency(ApplicationEventPublisher.class, this);  
   beanFactory.registerResolvableDependency(ApplicationContext.class, this);
   // 注册 事件监听器  
   beanFactory.addBeanPostProcessor(new ApplicationListenerDetector(this));
   // 如果存在bean名称为loadTimeWeaver的bean则注册一个
   BeanPostProcessor   if (beanFactory.containsBean(LOAD_TIME_WEAVER_BEAN_NAME)) {      
   beanFactory.addBeanPostProcessor(new LoadTimeWeaverAwareProcessor(beanFactory));      
   // Set a temporary ClassLoader for type matching.
   beanFactory.setTempClassLoader(new ContextTypeMatchClassLoader(beanFactory.getBeanClassLoader()));   }
   // 如果没有定义 "environment" 这个 bean,那么 Spring 会 "手动" 注册一个   
   if (!beanFactory.containsLocalBean(ENVIRONMENT_BEAN_NAME)) {   
   beanFactory.registerSingleton(ENVIRONMENT_BEAN_NAME, getEnvironment());  
   }   
   // 如果没有定义 "systemProperties" 这个 bean,那么 Spring 会 "手动" 注册一个
   if (!beanFactory.containsLocalBean(SYSTEM_PROPERTIES_BEAN_NAME)) {  
   beanFactory.registerSingleton(SYSTEM_PROPERTIES_BEAN_NAME, getEnvironment().getSystemProperties());   }  
   // 如果没有定义 "systemEnvironment" 这个 bean,那么 Spring 会 "手动" 注册一个  
   if (!beanFactory.containsLocalBean(SYSTEM_ENVIRONMENT_BEAN_NAME)) { 
   beanFactory.registerSingleton(SYSTEM_ENVIRONMENT_BEAN_NAME, 
   getEnvironment().getSystemEnvironment());   
   }}

看的出来,这个方法主要是对BeanFactory进行加工。 包括设置类加载器、事件监听器、系统环境,以及一些默认值。这里又来一个扩展点,我们瞅瞅咋回事。

image.png 可以看到这个构造方法只是赋值后续就不看了,看这个注释也已经很明显了。 给传过来的上下文创建一个ApplicationContextAwareProcessor。 看他的源码后面

package org.springframework.context.support;

import java.security.AccessControlContext;
import java.security.AccessController;
import java.security.PrivilegedAction;

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.Aware;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.beans.factory.config.EmbeddedValueResolver;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.ApplicationEventPublisherAware;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.EmbeddedValueResolverAware;
import org.springframework.context.EnvironmentAware;
import org.springframework.context.MessageSourceAware;
import org.springframework.context.ResourceLoaderAware;
import org.springframework.lang.Nullable;
import org.springframework.util.StringValueResolver;

// 注意,这里class前没有public修饰符,表明这个工具Spring没有打算给外部使用。
class ApplicationContextAwareProcessor implements BeanPostProcessor {

	private final ConfigurableApplicationContext applicationContext;

	private final StringValueResolver embeddedValueResolver;


	/**
	 * Create a new ApplicationContextAwareProcessor for the given context.
	 * 使用给定的应用上下文创建一个ApplicationContextAwareProcessor实例,通常该方法
	 * 由应用上下文对象自己调用,比如在类AbstractApplicationContext中 : 
	 * new ApplicationContextAwareProcessor(this)
	 */
	public ApplicationContextAwareProcessor(ConfigurableApplicationContext applicationContext) {
		this.applicationContext = applicationContext;
		this.embeddedValueResolver = new EmbeddedValueResolver(applicationContext.getBeanFactory());
	}


	// 接口BeanPostProcessor规定的方法,会在bean创建时,实例化后,初始化前,对bean对象应用
	@Override
	@Nullable
	public Object postProcessBeforeInitialization(final Object bean, String beanName) throws BeansException {
		AccessControlContext acc = null;

		if (System.getSecurityManager() != null &&
				(bean instanceof EnvironmentAware || bean instanceof EmbeddedValueResolverAware ||
						bean instanceof ResourceLoaderAware || bean instanceof ApplicationEventPublisherAware ||
						bean instanceof MessageSourceAware || bean instanceof ApplicationContextAware)) {
			acc = this.applicationContext.getBeanFactory().getAccessControlContext();
		}

		if (acc != null) {
			AccessController.doPrivileged((PrivilegedAction<Object>) () -> {
				// 检查bean上是否实现了某个Aware接口,有的话做相应调用
				invokeAwareInterfaces(bean);
				return null;
			}, acc);
		}
		else {
			// 检查bean上是否实现了某个Aware接口,有的话做相应调用
			invokeAwareInterfaces(bean);
		}

		// 返回处理后的bean
		return bean;
	}

	// 检查bean上是否实现了某个Aware接口,有的话做相应调用
	private void invokeAwareInterfaces(Object bean) {
		if (bean instanceof Aware) {
			if (bean instanceof EnvironmentAware) {
				((EnvironmentAware) bean).setEnvironment(this.applicationContext.getEnvironment());
			}
			if (bean instanceof EmbeddedValueResolverAware) {
				((EmbeddedValueResolverAware) bean).setEmbeddedValueResolver(this.embeddedValueResolver);
			}
			if (bean instanceof ResourceLoaderAware) {
				((ResourceLoaderAware) bean).setResourceLoader(this.applicationContext);
			}
			if (bean instanceof ApplicationEventPublisherAware) {
				((ApplicationEventPublisherAware) bean).setApplicationEventPublisher(this.applicationContext);
			}
			if (bean instanceof MessageSourceAware) {
				((MessageSourceAware) bean).setMessageSource(this.applicationContext);
			}
			if (bean instanceof ApplicationContextAware) {
				((ApplicationContextAware) bean).setApplicationContext(this.applicationContext);
			}
		}
	}

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

}

看的出来,这个就是用来扩展用。 image.png

意思就是,如果某个 bean 依赖于以下几个接口的实现类,在自动装配的时候忽略它们,Spring 会通过其他方式来处理这些依赖。 先不管这个Aware什么时候调用的,我先演示一下。

package Test;

import org.springframework.beans.BeansException;
import org.springframework.context.*;
import org.springframework.core.env.Environment;
import org.springframework.core.io.ResourceLoader;
import org.springframework.util.StringValueResolver;

public class myLunch implements EnvironmentAware, EmbeddedValueResolverAware, ResourceLoaderAware, ApplicationEventPublisherAware, MessageSourceAware,ApplicationContextAware{
    //食材1
    private String material1;
    //食材2
    private String material2;
    //默认食材
    myLunch(String material1,String material2){
        this.material1=material1;
        this.material2=material2;
        System.out.println("食材:"+material1+"和"+material2);
    }
    //放入食材1
    public void setMaterial1(String material1) {
        this.material1 = material1;
    }
    //放入食材2
    public void setMaterial2(String material2) {
        this.material2 = material2;
    }
    //自己做
    public void cook() {
        System.out.println("我给自己做了午饭:"+this.material1+"炒"+this.material2);
    }

    @Override
    public void setEnvironment(Environment environment) {
        System.out.println("A");
    }
    @Override
    public void setEmbeddedValueResolver(StringValueResolver resolver) {
        System.out.println("B");
    }
    @Override
    public void setResourceLoader(ResourceLoader resourceLoader) {
        System.out.println("C");
    }
    @Override
    public void setApplicationEventPublisher(ApplicationEventPublisher applicationEventPublisher) {
        System.out.println("D");
    }
    @Override
    public void setMessageSource(MessageSource messageSource) {
        System.out.println("E");
    }
    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        System.out.println("F");
    }
}

image.png 嘿嘿,还挺好用的。
第六行

postProcessBeanFactory(beanFactory);

又是一个扩展点

public class myLunch implements BeanFactoryPostProcessor {
    //食材1
    private String material1;
    //食材2
    private String material2;
    //默认食材
    myLunch(String material1,String material2){
        this.material1=material1;
        this.material2=material2;
        System.out.println("食材:"+material1+"和"+material2);
    }
    //放入食材1
    public void setMaterial1(String material1) {
        this.material1 = material1;
    }
    //放入食材2
    public void setMaterial2(String material2) {
        this.material2 = material2;
    }
    //自己做
    public void cook() {
        System.out.println("我给自己做了午饭:"+this.material1+"炒"+this.material2);
    }


    @Override
    public void postProcessBeanFactory(ConfigurableListableBeanFactory configurableListableBeanFactory) throws BeansException {
        System.out.println("6666");
    }
}

image.png

如果有Bean实现了BeanFactoryPostProcessor接口,那么在容器初始化以后,Spring 会负责调用里面的 postProcessBeanFactory 方法。具体的子类可以在这步的时候添加一些特殊的 BeanFactoryPostProcessor 的实现类或做点什么事。
第七行

StartupStep beanPostProcess = this.applicationStartup.start("spring.context.beans.post-process");

也是没什么用,表明要开始执行Baen的后置处理器。
第八行

invokeBeanFactoryPostProcessors(beanFactory);

主要作用是调用BeanFactoryPostProcessor各个实现类的postProcessBeanFactory(factory) 方法

image.png

来源[死磕 Spring] --- 深入分析 ApplicationContext 的 refresh() - Java 技术驿站 (cmsblogs.com)

  public static void invokeBeanFactoryPostProcessors(
                ConfigurableListableBeanFactory beanFactory, List<BeanFactoryPostProcessor> beanFactoryPostProcessors) {
    
            // 定义一个 set 保存所有的 BeanFactoryPostProcessors
            Set<String> processedBeans = new HashSet<>();
    
            // 如果当前 BeanFactory 为 BeanDefinitionRegistry
            if (beanFactory instanceof BeanDefinitionRegistry) {
                BeanDefinitionRegistry registry = (BeanDefinitionRegistry) beanFactory;
                // BeanFactoryPostProcessor 集合
                List<BeanFactoryPostProcessor> regularPostProcessors = new ArrayList<>();
                // BeanDefinitionRegistryPostProcessor 集合
                List<BeanDefinitionRegistryPostProcessor> registryProcessors = new ArrayList<>();
    
                // 迭代注册的 beanFactoryPostProcessors
                for (BeanFactoryPostProcessor postProcessor : beanFactoryPostProcessors) {
                    // 如果是 BeanDefinitionRegistryPostProcessor,则调用 postProcessBeanDefinitionRegistry 进行注册,
                    // 同时加入到 registryProcessors 集合中
                    if (postProcessor instanceof BeanDefinitionRegistryPostProcessor) {
                        BeanDefinitionRegistryPostProcessor registryProcessor =
                                (BeanDefinitionRegistryPostProcessor) postProcessor;
                        registryProcessor.postProcessBeanDefinitionRegistry(registry);
                        registryProcessors.add(registryProcessor);
                    }
                    else {
                        // 否则当做普通的 BeanFactoryPostProcessor 处理
                        // 添加到 regularPostProcessors 集合中即可,便于后面做后续处理
                        regularPostProcessors.add(postProcessor);
                    }
                }
    
                // 用于保存当前处理的 BeanDefinitionRegistryPostProcessor
                List<BeanDefinitionRegistryPostProcessor> currentRegistryProcessors = new ArrayList<>();
    
                // 首先处理实现了 PriorityOrdered (有限排序接口)的 BeanDefinitionRegistryPostProcessor
                String[] postProcessorNames =
                        beanFactory.getBeanNamesForType(BeanDefinitionRegistryPostProcessor.class, true, false);
                for (String ppName : postProcessorNames) {
                    if (beanFactory.isTypeMatch(ppName, PriorityOrdered.class)) {
                        currentRegistryProcessors.add(beanFactory.getBean(ppName, BeanDefinitionRegistryPostProcessor.class));
                        processedBeans.add(ppName);
                    }
                }
    
                // 排序
                sortPostProcessors(currentRegistryProcessors, beanFactory);
    
                // 加入registryProcessors集合
                registryProcessors.addAll(currentRegistryProcessors);
    
                // 调用所有实现了 PriorityOrdered 的 BeanDefinitionRegistryPostProcessors 的 postProcessBeanDefinitionRegistry()
                invokeBeanDefinitionRegistryPostProcessors(currentRegistryProcessors, registry);
    
                // 清空,以备下次使用
                currentRegistryProcessors.clear();
    
                // 其次,调用是实现了 Ordered(普通排序接口)的 BeanDefinitionRegistryPostProcessors
                // 逻辑和 上面一样
                postProcessorNames = beanFactory.getBeanNamesForType(BeanDefinitionRegistryPostProcessor.class, true, false);
                for (String ppName : postProcessorNames) {
                    if (!processedBeans.contains(ppName) && beanFactory.isTypeMatch(ppName, Ordered.class)) {
                        currentRegistryProcessors.add(beanFactory.getBean(ppName, BeanDefinitionRegistryPostProcessor.class));
                        processedBeans.add(ppName);
                    }
                }
                sortPostProcessors(currentRegistryProcessors, beanFactory);
                registryProcessors.addAll(currentRegistryProcessors);
                invokeBeanDefinitionRegistryPostProcessors(currentRegistryProcessors, registry);
                currentRegistryProcessors.clear();
    
                // 最后调用其他的 BeanDefinitionRegistryPostProcessors
                boolean reiterate = true;
                while (reiterate) {
                    reiterate = false;
                    // 获取 BeanDefinitionRegistryPostProcessor
                    postProcessorNames = beanFactory.getBeanNamesForType(BeanDefinitionRegistryPostProcessor.class, true, false);
                    for (String ppName : postProcessorNames) {
    
                        // 没有包含在 processedBeans 中的(因为包含了的都已经处理了)
                        if (!processedBeans.contains(ppName)) {
                            currentRegistryProcessors.add(beanFactory.getBean(ppName, BeanDefinitionRegistryPostProcessor.class));
                            processedBeans.add(ppName);
                            reiterate = true;
                        }
                    }
    
                    // 与上面处理逻辑一致
                    sortPostProcessors(currentRegistryProcessors, beanFactory);
                    registryProcessors.addAll(currentRegistryProcessors);
                    invokeBeanDefinitionRegistryPostProcessors(currentRegistryProcessors, registry);
                    currentRegistryProcessors.clear();
                }
    
                // 调用所有 BeanDefinitionRegistryPostProcessor (包括手动注册和通过配置文件注册)
                // 和 BeanFactoryPostProcessor(只有手动注册)的回调函数(postProcessBeanFactory())
                invokeBeanFactoryPostProcessors(registryProcessors, beanFactory);
                invokeBeanFactoryPostProcessors(regularPostProcessors, beanFactory);
            }
    
            else {
                // 如果不是 BeanDefinitionRegistry 只需要调用其回调函数(postProcessBeanFactory())即可
                invokeBeanFactoryPostProcessors(beanFactoryPostProcessors, beanFactory);
            }
    
            //
            String[] postProcessorNames =
                    beanFactory.getBeanNamesForType(BeanFactoryPostProcessor.class, true, false);
    
            // 这里同样需要区分 PriorityOrdered 、Ordered 和 no Ordered
            List<BeanFactoryPostProcessor> priorityOrderedPostProcessors = new ArrayList<>();
            List<String> orderedPostProcessorNames = new ArrayList<>();
            List<String> nonOrderedPostProcessorNames = new ArrayList<>();
            for (String ppName : postProcessorNames) {
                // 已经处理过了的,跳过
                if (processedBeans.contains(ppName)) {
                    // skip - already processed in first phase above
                }
                // PriorityOrdered
                else if (beanFactory.isTypeMatch(ppName, PriorityOrdered.class)) {
                    priorityOrderedPostProcessors.add(beanFactory.getBean(ppName, BeanFactoryPostProcessor.class));
                }
                // Ordered
                else if (beanFactory.isTypeMatch(ppName, Ordered.class)) {
                    orderedPostProcessorNames.add(ppName);
                }
                // no Ordered
                else {
                    nonOrderedPostProcessorNames.add(ppName);
                }
            }
    
            // First, PriorityOrdered 接口
            sortPostProcessors(priorityOrderedPostProcessors, beanFactory);
            invokeBeanFactoryPostProcessors(priorityOrderedPostProcessors, beanFactory);
    
            // Next, Ordered 接口
            List<BeanFactoryPostProcessor> orderedPostProcessors = new ArrayList<>();
            for (String postProcessorName : orderedPostProcessorNames) {
                orderedPostProcessors.add(beanFactory.getBean(postProcessorName, BeanFactoryPostProcessor.class));
            }
            sortPostProcessors(orderedPostProcessors, beanFactory);
            invokeBeanFactoryPostProcessors(orderedPostProcessors, beanFactory);
    
            // Finally, no ordered
            List<BeanFactoryPostProcessor> nonOrderedPostProcessors = new ArrayList<>();
            for (String postProcessorName : nonOrderedPostProcessorNames) {
                nonOrderedPostProcessors.add(beanFactory.getBean(postProcessorName, BeanFactoryPostProcessor.class));
            }
            invokeBeanFactoryPostProcessors(nonOrderedPostProcessors, beanFactory);
    
            // Clear cached merged bean definitions since the post-processors might have
            // modified the original metadata, e.g. replacing placeholders in values...
            beanFactory.clearMetadataCache();
        }

就是对所有的 BeanDefinitionRegistryPostProcessors 、手动注册的 BeanFactoryPostProcessor 以及通过配置文件方式的 BeanFactoryPostProcessor 按照 PriorityOrdered 、 Ordered、no ordered 三种方式分开处理、调用。
第九行

registerBeanPostProcessors(beanFactory);

扩展点 注册 BeanPostProcessor 的实现类,注意不是BeanFactoryPostProcessor。 此接口有两个方法: postProcessBeforeInitialization 和 postProcessAfterInitialization分别会在Bean初始化之前和初始化之后得到执行。

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

   // WARNING: Although it may appear that the body of this method can be easily
   // refactored to avoid the use of multiple loops and multiple lists, the use
   // of multiple lists and multiple passes over the names of processors is
   // intentional. We must ensure that we honor the contracts for PriorityOrdered
   // and Ordered processors. Specifically, we must NOT cause processors to be
   // instantiated (via getBean() invocations) or registered in the ApplicationContext
   // in the wrong order.
   //
   // Before submitting a pull request (PR) to change this method, please review the
   // list of all declined PRs involving changes to PostProcessorRegistrationDelegate
   // to ensure that your proposal does not result in a breaking change:
   // https://github.com/spring-projects/spring-framework/issues?q=PostProcessorRegistrationDelegate+is%3Aclosed+label%3A%22status%3A+declined%22

   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));
}

第十行

beanPostProcess.end();

没什么用,明beanPostProcess过程结束,与第五行 StartupStep contextRefresh = this.applicationStartup.start("spring.context.refresh");对应。
第十一行

// Initialize message source for this context.
initMessageSource();

初始化当前 ApplicationContext 的 MessageSource,有想了解国际化的相关知识可以深入研究一下。
第十二行

// Initialize event multicaster for this context.
initApplicationEventMulticaster();

这个方法主要为初始化当前 ApplicationContext 的事件广播器

  protected void initApplicationEventMulticaster() {
            ConfigurableListableBeanFactory beanFactory = getBeanFactory();
    
            // 如果存在 applicationEventMulticaster bean,则获取赋值
            if (beanFactory.containsLocalBean(APPLICATION_EVENT_MULTICASTER_BEAN_NAME)) {
                this.applicationEventMulticaster =
                        beanFactory.getBean(APPLICATION_EVENT_MULTICASTER_BEAN_NAME, ApplicationEventMulticaster.class);
                if (logger.isDebugEnabled()) {
                    logger.debug("Using ApplicationEventMulticaster [" + this.applicationEventMulticaster + "]");
                }
            }
            else {
                // 没有则新建 SimpleApplicationEventMulticaster,并完成 bean 的注册
                this.applicationEventMulticaster = new SimpleApplicationEventMulticaster(beanFactory);
                beanFactory.registerSingleton(APPLICATION_EVENT_MULTICASTER_BEAN_NAME, this.applicationEventMulticaster);
                if (logger.isDebugEnabled()) {
                    logger.debug("Unable to locate ApplicationEventMulticaster with name '" +
                            APPLICATION_EVENT_MULTICASTER_BEAN_NAME +
                            "': using default [" + this.applicationEventMulticaster + "]");
                }
            }
        }
    

第十三行

// Initialize other special beans in specific context subclasses.
onRefresh();

扩展点 第十四行

// Check for listener beans and register them.
registerListeners();

在所有 bean 中查找 listener bean,然后注册到广播器中。

protected void registerListeners() {
      //先添加手动set的一些监听器
      for (ApplicationListener<?> listener : getApplicationListeners()) {
         getApplicationEventMulticaster().addApplicationListener(listener);
      }

      //取到监听器的名称,设置到广播器
      String[] listenerBeanNames = getBeanNamesForType(ApplicationListener.class, true, false);
      for (String listenerBeanName : listenerBeanNames) {
         getApplicationEventMulticaster().addApplicationListenerBean(listenerBeanName);
      }

      // 如果存在早期应用事件,发布
      Set<ApplicationEvent> earlyEventsToProcess = this.earlyApplicationEvents;
      this.earlyApplicationEvents = null;
      if (earlyEventsToProcess != null) {
         for (ApplicationEvent earlyEvent : earlyEventsToProcess) {
            getApplicationEventMulticaster().multicastEvent(earlyEvent);
         }
      }
   }

第十五行

// Instantiate all remaining (non-lazy-init) singletons.
finishBeanFactoryInitialization(beanFactory);

这个方法就是负责初始化所有的没有设置懒加载的singleton bean。

关于这个方法及后续的GetBean()流程我会在下一篇进行详细说明。