Spring 启动流程--BeanDefinitionRegistryPostProcessor与BeanFactoryPostProcessor调用时机

1.先看看这两个接口

public interface BeanFactoryPostProcessor {

	/**
	 * Modify the application context's internal bean factory after its standard
	 * initialization. All bean definitions will have been loaded, but no beans
	 * will have been instantiated yet. This allows for overriding or adding
	 * properties even to eager-initializing beans.
	 * @param beanFactory the bean factory used by the application context
	 * @throws org.springframework.beans.BeansException in case of errors
	 */
	void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException;

}

// 因为BeanDefinitionRegistryPostProcessor 是 BeanFactoryPostProcessor 的子接口,则
// BeanDefinitionRegistryPostProcessor 的实现类,将会实现这两个接口的两个方法
public interface BeanDefinitionRegistryPostProcessor extends BeanFactoryPostProcessor {

	/**
	 * Modify the application context's internal bean definition registry after its
	 * standard initialization. All regular bean definitions will have been loaded,
	 * but no beans will have been instantiated yet. This allows for adding further
	 * bean definitions before the next post-processing phase kicks in.
	 * @param registry the bean definition registry used by the application context
	 * @throws org.springframework.beans.BeansException in case of errors
	 */
	void postProcessBeanDefinitionRegistry(BeanDefinitionRegistry registry) throws BeansException;

}

2.启动过程中的执行过程

2.1 启动Spring

	@Test
	public void test01(){
		AnnotationConfigApplicationContext applicationContext  = 
				new AnnotationConfigApplicationContext(ExtConfig.class);

		applicationContext.close();
	}

2.2 调用refresh() 方法

	public AnnotationConfigApplicationContext(Class<?>... annotatedClasses) {
		this();
		register(annotatedClasses);
		refresh();
	}
@Override
	public void refresh() throws BeansException, IllegalStateException {
		synchronized (this.startupShutdownMonitor) {
			// Prepare this context for refreshing.
			prepareRefresh();

			// Tell the subclass to refresh the internal bean factory.
			ConfigurableListableBeanFactory beanFactory = obtainFreshBeanFactory();

			// Prepare the bean factory for use in this context.
			prepareBeanFactory(beanFactory);

			try {
				// Allows post-processing of the bean factory in context subclasses.
				postProcessBeanFactory(beanFactory);

                    //调用注册在工厂的处理器BeanFactoryPostProcessors
				invokeBeanFactoryPostProcessors(beanFactory);

				// Register bean processors that intercept bean creation.
				registerBeanPostProcessors(beanFactory);

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

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

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

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

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

				// Last step: publish corresponding event.
				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();
			}
		}
	}

2.3详细来看下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()));
		}
	}

2.4实例化BeanFactoryPostProcessors,并将其排序后依次调用

  • 先处理实现了 BeanDefinitionRegistryPostProcessor 接口的

  • 从容器中获取BeanDefinitionRegistryPostProcessor 类型的beanName

  • 根据其优先级顺序,依次调用从 BeanDefinitionRegistryPostProcessor 接口中实现的 postProcessBeanDefinitionRegistry()方法

  • 再调用所有从BeanFactoryPostProcessor 接口中实现的 postProcessBeanFactory()方法

  • 再处理实现了 BeanDefinitionRegistryPostProcessor 接口的,但会排除实现了 BeanDefinitionRegistryPostProcessor 接口的

  • 也是按优先级循序来调用其postProcessBeanFactory()方法

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

		// Invoke BeanDefinitionRegistryPostProcessors first, if any.
		Set<String> processedBeans = new HashSet<String>();

		if (beanFactory instanceof BeanDefinitionRegistry) {
			BeanDefinitionRegistry registry = (BeanDefinitionRegistry) beanFactory;
			List<BeanFactoryPostProcessor> regularPostProcessors = new LinkedList<BeanFactoryPostProcessor>();
			List<BeanDefinitionRegistryPostProcessor> registryProcessors = new LinkedList<BeanDefinitionRegistryPostProcessor>();

			for (BeanFactoryPostProcessor postProcessor : beanFactoryPostProcessors) {
				if (postProcessor instanceof BeanDefinitionRegistryPostProcessor) {
					BeanDefinitionRegistryPostProcessor registryProcessor =
							(BeanDefinitionRegistryPostProcessor) postProcessor;
					registryProcessor.postProcessBeanDefinitionRegistry(registry);
					registryProcessors.add(registryProcessor);
				}
				else {
					regularPostProcessors.add(postProcessor);
				}
			}

			// Do not initialize FactoryBeans here: We need to leave all regular beans
			// uninitialized to let the bean factory post-processors apply to them!
			// Separate between BeanDefinitionRegistryPostProcessors that implement
			// PriorityOrdered, Ordered, and the rest.
			List<BeanDefinitionRegistryPostProcessor> currentRegistryProcessors = new ArrayList<BeanDefinitionRegistryPostProcessor>();


        // 首先 调用实现了PriorityOrdered 接口的BeanDefinitionRegistryPostProcessors 
			String[] postProcessorNames =
					beanFactory.getBeanNamesForType(BeanDefinitionRegistryPostProcessor.class, true, false);
        //拿到所有BeanDefinitionRegistryPostProcessors 类型的beanname,循环判断当前是否实现了PriorityOrdered优先级接口
			for (String ppName : postProcessorNames) {
				if (beanFactory.isTypeMatch(ppName, PriorityOrdered.class)) {
    // 如果实现了,则通过getBean()方法来获取对应的对象,并加入到List中(currentRegistryProcessors)
					currentRegistryProcessors.add(beanFactory.getBean(ppName, BeanDefinitionRegistryPostProcessor.class));
// 把每次新添加的beanName 保存起来,代表其已经被处理过了,下面将会判断正在处理的BeanDefinitionRegistryPostProcessor 以前是否处理过
					processedBeans.add(ppName);
				}
			}
			// 排序这些 BeanDefinitionRegistryPostProcessor
			sortPostProcessors(currentRegistryProcessors, beanFactory);
			// registryProcessors 用来保存所有的BeanDefinitionRegistryPostProcessor类型的bean
			registryProcessors.addAll(currentRegistryProcessors);
			//BeanDefinitionRegistryPostProcessor 依次回调其postProcessBeanDefinitionRegistry()方法
			invokeBeanDefinitionRegistryPostProcessors(currentRegistryProcessors, registry);
			// 清空list,接下来将被拿来存放实现了Ordered 接口的
			currentRegistryProcessors.clear();

            // 再次拿到所有的 BeanDefinitionRegistryPostProcessor 类型的 beanName
			postProcessorNames = beanFactory.getBeanNamesForType(BeanDefinitionRegistryPostProcessor.class, true, false);
			// 又一次循环遍历它们
			for (String ppName : postProcessorNames) {
			// 如果当前的这个beanName,在上面没有处理过,且还实现了Ordered接口
				if (!processedBeans.contains(ppName) && beanFactory.isTypeMatch(ppName, Ordered.class)) {
					// 则获取到其实例,并加入到currentRegistryProcessors 集合中
					currentRegistryProcessors.add(beanFactory.getBean(ppName, BeanDefinitionRegistryPostProcessor.class));
					// 把每次新添加的beanName 保存起来,代表其已经被处理过了
					processedBeans.add(ppName);
				}
			}
			// 排序
			sortPostProcessors(currentRegistryProcessors, beanFactory);
			// registryProcessors 用来保存所有的BeanDefinitionRegistryPostProcessor类型的bean
			registryProcessors.addAll(currentRegistryProcessors);
			// 回调其postProcessBeanDefinitionRegistry()方法
			invokeBeanDefinitionRegistryPostProcessors(currentRegistryProcessors, registry);
			// 清空list,接下来将被拿来存放其他的 BeanDefinitionRegistryPostProcessor 的实例
			currentRegistryProcessors.clear();

			// Finally, invoke all other BeanDefinitionRegistryPostProcessors until no further ones appear.
            // 最终调用余下的BeanDefinitionRegistryPostProcessors,直到容器中不再有该类型的定义信息;因为 //BeanDefinitionRegistryPostProcessors 中可以新注册Bean,此Bean也可能是BeanDefinitionRegistryPostProcessors 类型的,所以此需要循环
            //直到已经没有需要处理的了
			boolean reiterate = true;
			while (reiterate) {
				reiterate = false;
				// 依然是拿到所有的 BeanDefinitionRegistryPostProcessor 类型的 beanName
				postProcessorNames = beanFactory.getBeanNamesForType(BeanDefinitionRegistryPostProcessor.class, true, false);
				// 挨个遍历
				for (String ppName : postProcessorNames) {
					// 如果发现有前面没有处理过的 
					if (!processedBeans.contains(ppName)) {
						// 则将其添加到 集合中
						currentRegistryProcessors.add(beanFactory.getBean(ppName, BeanDefinitionRegistryPostProcessor.class));
						// 把每次新添加的beanName 保存起来,代表其已经被处理过了
						processedBeans.add(ppName);
						// 添加了新的 BeanDefinitionRegistryPostProcessor ,则表示还需要再循环一遍
						reiterate = true;
					}
				}
				// 排序上面循环中添加的
				sortPostProcessors(currentRegistryProcessors, beanFactory);
				//  registryProcessors 用来保存所有的BeanDefinitionRegistryPostProcessor类型的bean
				registryProcessors.addAll(currentRegistryProcessors);
				// 执行回调
				invokeBeanDefinitionRegistryPostProcessors(currentRegistryProcessors, registry);
				// 清空集合
				currentRegistryProcessors.clear();
			}

            //现在,调用到目前为止处理的所有处理器的postProcessBeanFactory回调(因为实现BeanDefinitionRegistryPostProcessor接口的类,也是
            //BeanFactoryPostProcessor 类型的子类,现在就来回调从BeanFactoryPostProcessor接口中继承来的postProcessBeanFactory()方法 )
            // registryProcessors 保存了上面获取到的所有的BeanDefinitionRegistryPostProcessor bean
			invokeBeanFactoryPostProcessors(registryProcessors, 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!
        // 从容器中获取所有BeanFactoryPostProcessor 类型的BeanName数组
		String[] postProcessorNames =
				beanFactory.getBeanNamesForType(BeanFactoryPostProcessor.class, true, false);

		// Separate between BeanFactoryPostProcessors that implement PriorityOrdered,
		// Ordered, and the rest.
		List<BeanFactoryPostProcessor> priorityOrderedPostProcessors = new ArrayList<BeanFactoryPostProcessor>();
		List<String> orderedPostProcessorNames = new ArrayList<String>();
		List<String> nonOrderedPostProcessorNames = new ArrayList<String>();
        // 遍历所有的BeanFactoryPostProcessor类型BeanName数组
		for (String ppName : postProcessorNames) {
               // 如果在第一阶段执行过的BeanFactoryPostProcessor 将在这跳过
//processedBeans 保存的是实现了BeanDefinitionRegistryPostProcessor 接口的全类名,而BeanDefinitionRegistryPostProcessor 又是BeanFactoryPostProcessors 的子接口,且其postProcessBeanFactory方法已经在前面调用过了,此处将会跳过其调用
			if (processedBeans.contains(ppName)) {
				// skip - already processed in first phase above
			}
                // 如果是实现了PriorityOrdered 接口的,优先创建
                //如果容器中没有,调用beanFactory.getBean方法,则会创建当前bean
			else if (beanFactory.isTypeMatch(ppName, PriorityOrdered.class)) {
				// 将实现了PriorityOrdered 接口的 BeanFactoryPostProcessor 实例添加到 priorityOrderedPostProcessors List中
				priorityOrderedPostProcessors.add(beanFactory.getBean(ppName, BeanFactoryPostProcessor.class));
			}
                //将实现了Ordered接口的,将其beanName添加到下面数组中
			else if (beanFactory.isTypeMatch(ppName, Ordered.class)) {
			// 将实现了Ordered接口的 BeanFactoryPostProcessor 实例添加到 orderedPostProcessorNames List中
				orderedPostProcessorNames.add(ppName);
			}
			else {
                //没有实现前两种接口的,将其beanName添加到下面的List中
				nonOrderedPostProcessorNames.add(ppName);
			}
		}


        // 首先,先排序实现了 PriorityOrdered 接口的BeanFactoryPostProcessors 
		sortPostProcessors(priorityOrderedPostProcessors, beanFactory);
		//然后依次调用它的postProcessBeanFactory()方法
		invokeBeanFactoryPostProcessors(priorityOrderedPostProcessors, beanFactory);

		//接下来排序实现了创建实现了Ordered接口的
		List<BeanFactoryPostProcessor> orderedPostProcessors = new ArrayList<BeanFactoryPostProcessor>();
		for (String postProcessorName : orderedPostProcessorNames) {
			orderedPostProcessors.add(beanFactory.getBean(postProcessorName, BeanFactoryPostProcessor.class));
		}
        // 排序 Ordered接口的BeanFactoryPostProcessors ,然后依次调用它    
		sortPostProcessors(orderedPostProcessors, beanFactory);
		invokeBeanFactoryPostProcessors(orderedPostProcessors, beanFactory);

		// 最后实例化,并调用其他的 BeanFactoryPostProcessors 
		List<BeanFactoryPostProcessor> nonOrderedPostProcessors = new ArrayList<BeanFactoryPostProcessor>();
		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();
	}

2.5 依次调用BeanDefinitionRegistryPostProcessor 的postProcessBeanDefinitionRegistry方法

	private static void invokeBeanDefinitionRegistryPostProcessors(
			Collection<? extends BeanDefinitionRegistryPostProcessor> postProcessors, BeanDefinitionRegistry registry) {

		for (BeanDefinitionRegistryPostProcessor postProcessor : postProcessors) {
			postProcessor.postProcessBeanDefinitionRegistry(registry);
		}
	}

2.6依次回调其postProcessBeanFactory方法,并将beanFactory实例传入

	private static void invokeBeanFactoryPostProcessors(
			Collection<? extends BeanFactoryPostProcessor> postProcessors, ConfigurableListableBeanFactory beanFactory) {

		for (BeanFactoryPostProcessor postProcessor : postProcessors) {
			postProcessor.postProcessBeanFactory(beanFactory);
		}
	}

你可能感兴趣的:(Spring)