代码


    @Override
    public void refresh() throws BeansException, IllegalStateException {
        synchronized (this.startupShutdownMonitor) {
            // Prepare this context for refreshing.
            prepareRefresh();

            // 获取spring bean工厂
            ConfigurableListableBeanFactory beanFactory = obtainFreshBeanFactory();

            // Prepare the bean factory for use in this context.
            // 这个方法执行完成, spring的bean单例容器中会存在三个bean,
            // 分别是systemEnvironment, environment, systemProperties
            // 同时会添加ApplicationContextAwareProcessor的后置处理器, 这个处理器没有走
            // spring的bean初始化, 是在内部直接new出来的, 该处理器是用来处理实现了
            // ApplicationContextAware接口的bean, 调用重写的set方法, 所以可以利用
            // 这种方法获取spring的上下文对象
            prepareBeanFactory(beanFactory);

            try {
                // 该方法没有做任何事, 内部无任何逻辑
                postProcessBeanFactory(beanFactory);

                // 调用后置处理器, 此方法太重要了, 在后续的源码解读系列中会解析它
                // 先大致总结下它做了什么事
                // 1. 处理手动添加的BeanFactoryPostProcessor
                //   1.1 调用手动添加的BeanDefinitionRegistryPostProcessor, 并添加到存储它的集合中,
                //       该集合名字为: registryProcessors
                //   1.2 存储手动添加的BeanFactoryPostProcessor,
                //       该集合名字为: regularPostProcessors
                //   注意: 上面这个步骤是if else逻辑, 存了一个另外一个就不会存了
                // 2. 执行BeanDefinitionRegistryPostProcessor类型且实现了PriorityOrdered接
                //    口的后置处理器. 默认执行spring内置BeanDefinitionRegistryPostProcessor
                //    后置处理器(ConfigurationClassPostProcessor), 这个后置处理器执行完之后,
                //    所有能被扫描出来的bean都以BeanDefinition的方式注册到bean工厂了
                // 3. 执行BeanDefinitionRegistryPostProcessor类型且实现了
                //    Ordered接口的后置处理器
                // 4. 执行以@Component方式添加的BeanDefinitionRegistryPostProcessor类型没实现
                //    Ordered和PriorityOrdered接口的后置处理器
                // 5. 执行regularPostProcessors和registryProcessors数据结构中
                //    BeanFactoryPostProcessor类型的后置处理器(在此处执行
                //    ConfigurationClassPostProcessor类的postProcessBeanFactory方法, 主要是
                //    为全配置类生成了cglib代理类的Class对象, 并修改它的beanDefinition信息为代
                //    理类的信息
                // 6. 执行以@Component形式添加并实现了PriorityOrdered接口的BeanFactoryPost
                //    Processor后置处理器
                // 7. 执行以@Component形式添加并实现了Ordered接口的BeanFactoryPost
                //    Processor后置处理器
                // 8. 执行以@Component形式添加并未实现PriorityOrdered和Ordered接口的Bean
                //    FactoryPostProcessor后置处理器
                invokeBeanFactoryPostProcessors(beanFactory);

                // 注册spring bean工厂的BeanPostProcessor
                // 其中包括spring内置的、扫描出来的(eg: 使用ImportBeanDefinitionRegistrar, AOP的实现方式)、
                // 自己手动添加的(手动添加BeanDefinitionRegistryPostProcessor,
                // 并在其中注册一个BeanPostProcessor的bean)
                //
                // 默认情况下, spring内置的3个BeanPostProcessor分别为:
                //   org.springframework.context.annotation.internalAutowiredAnnotationProcessor   => 处理@Autowired注解的
                //   org.springframework.context.annotation.internalRequiredAnnotationProcessor  => 处理@Required注解的
                //   org.springframework.context.annotation.internalCommonAnnotationProcessor  => 处理Common注解的后置处理器
                // 以及各种实现了PriorityOrdered接口、Ordered接口的BeanPostProcessor处理
                // 最主要的就是把这些bean通过spring bean工厂创建出来, 并添加到一个存放BeanPostProcessor的list中, 再利用广播
                // 机制调用
                // 我觉得这里用list而不用set的原因有两个
                // 1. list是有序的, 因为有些BeanPostProcessor会实现PriorityOrdered接口、Ordered接口, 所以要按照一定的顺序执行
                // 2. 广播机制时要遍历集合, list遍历速度快一些
                registerBeanPostProcessors(beanFactory);

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

                // Initialize event multicaster for this context.
                // 初始化spring事件驱动模型的执行者
                initApplicationEventMulticaster();

                // 该方法没有做任何事, 内部无任何逻辑
                onRefresh();

                // 注册自己手动添加的监听器和spring扫描出来的监听器
                // 手动添加的监听器: 调用spring上下文的addApplicationListener方法, eg: AnnotationConfigApplicationContext上下文的方法
                // spring扫描出来的监听器: 有@Component注解标识的监听器
                // 这里有人会问: 万一我一个监听器同时加了@Component注解也手动调用了addApplicationListener添加呢?
                // 没关系, 那就执行两次呗, 因为spring处理手动添加的和扫描出来的监听器是不一样的, 手动添加的是一个java 对象, 而spring扫描出来
                // 的监听器是一个bean, 所以这两个监听器是同一类型的不同对象
                // 但要注意的是, 手动添加的监听器是一个java object, 而spring扫描出来的是一个bean
                registerListeners();

                // 开始创建非抽象、非原型、非懒加载的bean 以及处理bean的自动装配
                finishBeanFactoryInitialization(beanFactory);

                // 完成刷新, 发布相应的事件
                finishRefresh();
            }

            catch (BeansException ex) {
                if (logger.isWarnEnabled()) {
                    logger.warn("Exception encountered during context initialization - " +
                            "cancelling refresh attempt: " + ex);
                }

                // Destroy already created singletons to avoid dangling resources.
                destroyBeans();

                // Reset 'active' flag.
                cancelRefresh(ex);

                // Propagate exception to caller.
                throw ex;
            }

            finally {
                // Reset common introspection caches in Spring's core, since we
                // might not ever need metadata for singleton beans anymore...
                resetCommonCaches();
            }
        }
    }
    

invokeBeanFactoryPostProcessors

AbstractApplicationContext#invokeBeanFactoryPostProcessors
	protected void invokeBeanFactoryPostProcessors(ConfigurableListableBeanFactory beanFactory) {
		PostProcessorRegistrationDelegate.invokeBeanFactoryPostProcessors(beanFactory, getBeanFactoryPostProcessors());

		// Detect a LoadTimeWeaver and prepare for weaving, if found in the meantime
		// (e.g. through an @Bean method registered by ConfigurationClassPostProcessor)
		if (beanFactory.getTempClassLoader() == null && beanFactory.containsBean(LOAD_TIME_WEAVER_BEAN_NAME)) {
			beanFactory.addBeanPostProcessor(new LoadTimeWeaverAwareProcessor(beanFactory));
			beanFactory.setTempClassLoader(new ContextTypeMatchClassLoader(beanFactory.getBeanClassLoader()));
		}
	}

invokeBeanFactoryPostProcessors

	public static void invokeBeanFactoryPostProcessors(
			ConfigurableListableBeanFactory beanFactory, List<BeanFactoryPostProcessor> beanFactoryPostProcessors) {

		// 如果有的话,首先调用 BeanDefinitionRegistryPostProcessors。
		Set<String> processedBeans = new HashSet<>();

		if (beanFactory instanceof BeanDefinitionRegistry) {
			BeanDefinitionRegistry registry = (BeanDefinitionRegistry) beanFactory;
//存储手动添加的BeanFactoryPostProcessor
			List<BeanFactoryPostProcessor> regularPostProcessors = new LinkedList<>();
//手动添加的BeanFactoryPostProcessor
			List<BeanDefinitionRegistryPostProcessor> registryPostProcessors =
					new LinkedList<>();
//一开始这个beanFactoryPostProcessors是空的,所以直接下面这个for循环不会走了
			for (BeanFactoryPostProcessor postProcessor : beanFactoryPostProcessors) {
				if (postProcessor instanceof BeanDefinitionRegistryPostProcessor) {
					BeanDefinitionRegistryPostProcessor registryPostProcessor =
							(BeanDefinitionRegistryPostProcessor) postProcessor;
					registryPostProcessor.postProcessBeanDefinitionRegistry(registry);
					registryPostProcessors.add(registryPostProcessor);
				}
				else {
					regularPostProcessors.add(postProcessor);
				}
			}
//不要在此处初始化 FactoryBeans:我们需要保留所有常规 bean 未初始化,
//以便让 bean 工厂后处理器应用于它们!将实现 PriorityOrdered、Ordered 和其余部分的 BeanDefinitionRegistryPostProcessor 分开。
			String[] postProcessorNames =
					beanFactory.getBeanNamesForType(BeanDefinitionRegistryPostProcessor.class, true, false);

			// new了一个给后置处理器排序的一个list
			List<BeanDefinitionRegistryPostProcessor> priorityOrderedPostProcessors = new ArrayList<>();
			for (String ppName : postProcessorNames) {
				if (beanFactory.isTypeMatch(ppName, PriorityOrdered.class)) {
					priorityOrderedPostProcessors.add(beanFactory.getBean(ppName, BeanDefinitionRegistryPostProcessor.class));
					processedBeans.add(ppName);
				}
			}
			sortPostProcessors(beanFactory, priorityOrderedPostProcessors);
			registryPostProcessors.addAll(priorityOrderedPostProcessors);
			invokeBeanDefinitionRegistryPostProcessors(priorityOrderedPostProcessors, registry);

			// Next, invoke the BeanDefinitionRegistryPostProcessors that implement Ordered.
			postProcessorNames = beanFactory.getBeanNamesForType(BeanDefinitionRegistryPostProcessor.class, true, false);
			List<BeanDefinitionRegistryPostProcessor> orderedPostProcessors = new ArrayList<>();
			for (String ppName : postProcessorNames) {
				if (!processedBeans.contains(ppName) && beanFactory.isTypeMatch(ppName, Ordered.class)) {
					orderedPostProcessors.add(beanFactory.getBean(ppName, BeanDefinitionRegistryPostProcessor.class));
					processedBeans.add(ppName);
				}
			}
			sortPostProcessors(beanFactory, orderedPostProcessors);
			registryPostProcessors.addAll(orderedPostProcessors);
			invokeBeanDefinitionRegistryPostProcessors(orderedPostProcessors, registry);

			// Finally, invoke all other BeanDefinitionRegistryPostProcessors until no further ones appear.
			boolean reiterate = true;
			while (reiterate) {
				reiterate = false;
				postProcessorNames = beanFactory.getBeanNamesForType(BeanDefinitionRegistryPostProcessor.class, true, false);
				for (String ppName : postProcessorNames) {
					if (!processedBeans.contains(ppName)) {
						BeanDefinitionRegistryPostProcessor pp = beanFactory.getBean(ppName, BeanDefinitionRegistryPostProcessor.class);
						registryPostProcessors.add(pp);
						processedBeans.add(ppName);
						pp.postProcessBeanDefinitionRegistry(registry);
						reiterate = true;
					}
				}
			}

			// Now, invoke the postProcessBeanFactory callback of all processors handled so far.
			invokeBeanFactoryPostProcessors(registryPostProcessors, beanFactory);
			invokeBeanFactoryPostProcessors(regularPostProcessors, beanFactory);
		}

		else {
			// Invoke factory processors registered with the context instance.
			invokeBeanFactoryPostProcessors(beanFactoryPostProcessors, beanFactory);
		}

		// Do not initialize FactoryBeans here: We need to leave all regular beans
		// uninitialized to let the bean factory post-processors apply to them!
		String[] postProcessorNames =
				beanFactory.getBeanNamesForType(BeanFactoryPostProcessor.class, true, false);

		// Separate between BeanFactoryPostProcessors that implement PriorityOrdered,
		// Ordered, and the rest.
		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
			}
			else if (beanFactory.isTypeMatch(ppName, PriorityOrdered.class)) {
				priorityOrderedPostProcessors.add(beanFactory.getBean(ppName, BeanFactoryPostProcessor.class));
			}
			else if (beanFactory.isTypeMatch(ppName, Ordered.class)) {
				orderedPostProcessorNames.add(ppName);
			}
			else {
				nonOrderedPostProcessorNames.add(ppName);
			}
		}

		// First, invoke the BeanFactoryPostProcessors that implement PriorityOrdered.
		sortPostProcessors(beanFactory, priorityOrderedPostProcessors);
		invokeBeanFactoryPostProcessors(priorityOrderedPostProcessors, beanFactory);

		// Next, invoke the BeanFactoryPostProcessors that implement Ordered.
		List<BeanFactoryPostProcessor> orderedPostProcessors = new ArrayList<>();
		for (String postProcessorName : orderedPostProcessorNames) {
			orderedPostProcessors.add(beanFactory.getBean(postProcessorName, BeanFactoryPostProcessor.class));
		}
		sortPostProcessors(beanFactory, orderedPostProcessors);
		invokeBeanFactoryPostProcessors(orderedPostProcessors, beanFactory);

		// Finally, invoke all other BeanFactoryPostProcessors.
		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();
	}