Spring源码解析(17)之refresh(5)-BeanFactoryPostProcessor执行流程源码分析

一、BeanFactoryPostProcessor与BeanDefinitionRegistryPostProcessor的区别

        这里我们把BeanDefinitionRegistryPostProcessor简称为:BDRPP,BeanFactoryPostProcessor简称为:BPP,首先BDRPP继承了BPP,所以它不仅有BPP的方法:postProcessBeanFactory并且有自己的方法:postProcessBeanDefinitionRegistry,那他们的区别主要是什么呢?我们先来看下BDRPP的方法,如下:

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;

}

public interface BeanDefinitionRegistry extends AliasRegistry {

	/**
	 * 将Bean定义注册到Bean注册中心
	 *
	 * 注意:该Bean定义必须支持父Bean定义及子Bean定义.
	 *
	 * @param beanName bean的名称
	 * @param beanDefinition bean的定义
	 * @throws BeanDefinitionStoreException
	 */
	void registerBeanDefinition(String beanName, BeanDefinition beanDefinition)
			throws BeanDefinitionStoreException;

	/**
	 * Remove the BeanDefinition for the given name.
	 * @param beanName the name of the bean instance to register
	 * @throws NoSuchBeanDefinitionException if there is no such bean definition
	 *
	 * 从Bean注册中心按照bean的名称移除Bean定义
	 */
	void removeBeanDefinition(String beanName) throws NoSuchBeanDefinitionException;

	/**
	 * Return the BeanDefinition for the given bean name.
	 * @param beanName name of the bean to find a definition for
	 * @return the BeanDefinition for the given name (never {@code null})
	 * @throws NoSuchBeanDefinitionException if there is no such bean definition
	 *
	 * 根据Bean的名称从Bean定义的注册中心获取Bean定义.
	 */
	BeanDefinition getBeanDefinition(String beanName) throws NoSuchBeanDefinitionException;

	/**
	 * Check if this registry contains a bean definition with the given name.
	 * @param beanName the name of the bean to look for
	 * @return if this registry contains a bean definition with the given name
	 *
	 * 判断Bean定义注册中心是否包括给定名称的Bean定义
	 */
	boolean containsBeanDefinition(String beanName);

	/**
	 * Return the names of all beans defined in this registry.
	 * @return the names of all beans defined in this registry,
	 * or an empty array if none defined
	 *
	 * 获取当前Bean定义注册中心的所有Bean定义的名称
	 */
	String[] getBeanDefinitionNames();

	/**
	 * Return the number of beans defined in the registry.
	 * @return the number of beans defined in the registry
	 *
	 * 获取当前Bean定义注册中心所有Bean定义的数量
	 */
	int getBeanDefinitionCount();

	/**
	 * Determine whether the given bean name is already in use within this registry,
	 * i.e. whether there is a local bean or alias registered under this name.
	 * @param beanName the name to check
	 * @return whether the given bean name is already in use
	 *
	 * 判断当前名称的Bean定义是否在Bean定义注册中心中已经使用了
	 */
	boolean isBeanNameInUse(String beanName);
}


        可以看得到BDRPP传入的参数是BeanDefinitionRegistry,这个接口的作用主要是对BeanDefinition的增删改查。我们通常在使用 Mybatis + Spring 时,经常用到的 org.mybatis.spring.mapper.MapperScannerConfigurer 就是一个BeanDefinitionRegistryPostProcessor。MapperScannerConfigurer 在 postProcessBeanDefinitionRegistry 方法中进行了一些操作, 主要是:扫描 basePackage 指定的目录,将该目录下的类(通常是 DAO/MAPPER 接口)封装成 BeanDefinition 并加载到 BeanFactory 中。 因此,我们可以看到我们项目中的 DAO(MAPPER)接口,通常都没有使用注解或 XML 的方式注册到 Spring 容器,但是我们还是可以在 Service 服务中, 使用 @Autowire 注解来将其注入到 Service 中,就是因为这个原因。

二、BeanFactoryPostProcessor执行流程源码分析

        首先我们先看一下下面这张图:

        大家先看懂这张图然后再去看源码,上面这张图就是BFPP的大概的执行流程,在Spring中他首先去执行外部的BFPP,也就是 :

	// beanFactory的真实类型为 DefaultListableBeanFactory
	protected void invokeBeanFactoryPostProcessors(ConfigurableListableBeanFactory beanFactory) {
		// 执行Bean工厂的所有后置处理器
		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()));
		}
	}

	public List<BeanFactoryPostProcessor> getBeanFactoryPostProcessors() {
		return this.beanFactoryPostProcessors;
	}

        getBeanFactoryPostProcessors获取Spring的自定义的BFPP默认是空的,有人问,那怎么样子才能获取得到值,这个就简单,我们在自定义的容器中重写方法调用对应的addBeanFactoryPostProcessor把我们自定义的BFPP放入进去,然后在这里获取就可以获取得到我们自定义的BFPP啦。

        我们先执行BDRPP,但是BDRPP呢又分为几种,第一种是实现了PriorityOrdered接口的,第二种是实现了Ordered接口的,第三种是没有实现有任何排序接口的BDRPP。最后呢在后面统一执行父类:BPP中的postProcessBeanFactory方法。

        接下来我们来看对应的源码实现,如果大家还不懂我上面画的那个大概流程图的话,大家可以先跳过对应的源码分析,先去看我后面画的BeanFactoryPostProcessor的流程图。

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

		/** 用来记录已经执行过的后置处理器 */
		Set<String> processedBeans = new HashSet<>();
		/**
		 * 判断beanFactory的类型是否为BeanDefinitionRegistry
		 * 此处beanFactory的类型为:DefaultListableBeanFactory,而DefaultListableBeanFactory是实现了BeanDefinitionRegistry接口的,
		 * 所以此处判断里面的结果为true.
		 *
		 * BeanDefinitionRegistry接口中定义了操作bean定义的常用方法。如:注册bean定义,移除bean定义,获取bean定义的数量,判断是否包含指定的bean定义等...
		 */
		if (beanFactory instanceof BeanDefinitionRegistry) {
			BeanDefinitionRegistry registry = (BeanDefinitionRegistry) beanFactory;

			// 用于存放普通的bean工厂的后置处理器
			List<BeanFactoryPostProcessor> regularPostProcessors = new ArrayList<>();

			/**
			 * 用于存放类型为BeanDefinitionRegistryPostProcessor的bean工厂后置处理器。BeanDefinitionRegistry是bean定义的注册中心。用来存放所有的bean定义.
			 * BeanDefinitionRegistryPostProcessor继承自BeanFactoryPostProcessor
			 */
			List<BeanDefinitionRegistryPostProcessor> registryProcessors = new ArrayList<>();

			/**
			 * 遍历所有的BeanFactoryPostProcessor,将普通的BeanFactoryPostProcessor和BeanDefinitionRegistryPostProcessor区分开.
			 */
			for (BeanFactoryPostProcessor postProcessor : beanFactoryPostProcessors) {
				if (postProcessor instanceof BeanDefinitionRegistryPostProcessor) {
					BeanDefinitionRegistryPostProcessor registryProcessor = (BeanDefinitionRegistryPostProcessor) postProcessor;
					// 直接执行BeanDefinitionRegistryPostProcessor接口的postProcessBeanDefinitionRegistry方法.
					registryProcessor.postProcessBeanDefinitionRegistry(registry);
					// 添加到registryProcessors中,用于最后执行postProcessBeanFactory方法
					registryProcessors.add(registryProcessor);
				} else {
					// 普通BeanFactoryPostProcessor,添加到regularPostProcessors中,用于最后执行postProcessBeanFactory方法.
					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.

			// 保存本次将要执行的BeanDefinitionRegistryPostProcessor.
			List<BeanDefinitionRegistryPostProcessor> currentRegistryProcessors = new ArrayList<>();

			// 下面的for循环中是找出所有实现了PriorityOrdered接口的BeanDefinitionRegistryPostProcessor实现类
			// 首先根据类型找出所有实现了BeanDefinitionRegistryPostProcessor接口的Bean的名称,然后依次循环遍历,判断是否实现了PriorityOrdered接口.
			String[] postProcessorNames =
					beanFactory.getBeanNamesForType(BeanDefinitionRegistryPostProcessor.class, true, false);
			for (String ppName : postProcessorNames) {
				if (beanFactory.isTypeMatch(ppName, PriorityOrdered.class)) {
					// 获取ppName对应的Bean实例,并添加到当前要执行的currentRegistryProcessors中

					// 此处会去创建容器中默认后置处理器对应的单实例bean
					// 此处的beanFactory.getBean会根据Bean的类型去创建Bean工厂后置处理器对象,有Bean的创建过程。
					currentRegistryProcessors.add(beanFactory.getBean(ppName, BeanDefinitionRegistryPostProcessor.class));
					// 把将要执行的bean的名称加入到processedBeans中,后续后判断是否已经执行。避免重复执行.
					processedBeans.add(ppName);
				}
			}

			// 根据是否实现了PriorityOrder,Order接口以及具体的order数值来排序.
			sortPostProcessors(currentRegistryProcessors, beanFactory);
			// 添加到registryProcessors,最后用于执行postProcessBeanFactory方法
			registryProcessors.addAll(currentRegistryProcessors);
			// 遍历当前要执行的所有BeanDefinitionRegistryPostProcessor,执行其postProcessBeanDefinitionRegistry方法.
			// 此处有一个重要的Bean定义注册中心的后置处理器:ConfigurationClassPostProcessor,配置类解析、条件注册的回调、方法及配置类的校验等操作
			invokeBeanDefinitionRegistryPostProcessors(currentRegistryProcessors, registry);
			// 执行完毕之后,清空currentRegistryProcessors
			currentRegistryProcessors.clear();

			// 查找所有实现了BeanDefinitionRegistryPostProcessor接口的实现类
			// 重复查找是因为上面执行完了所有的BeanDefinitionRegistryPostProcessor类之后,可能又新增了其他的BeanDefinitionRegistryPostProcessor。
			//    比如:有一个自定义的BeanDefinitionRegistryPostProcessor中实现了PriorityOrdered接口之后,同时实现了BeanDefinitionRegistryPostProcessor接口.
			postProcessorNames = beanFactory.getBeanNamesForType(BeanDefinitionRegistryPostProcessor.class, true, false);
			for (String ppName : postProcessorNames) {
				// 校验是否实现了Ordered接口,并且之前未执行过
				// 使用上述执行完毕之后记录的Set集合判断是否执行过.
				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);
			// 遍历所有的BeanDefinitionRegistryPostProcessor接口的实现类,
			//  并执行BeanDefinitionRegistryPostProcessor的postProcessBeanDefinitionRegistry方法
			invokeBeanDefinitionRegistryPostProcessors(currentRegistryProcessors, registry);
			// 清空
			currentRegistryProcessors.clear();

			// Finally, invoke all other BeanDefinitionRegistryPostProcessors until no further ones appear.
			// 最后,遍历其他除了实现Ordered接口和PriorityOrdered接口的BeanDefinitionRegistryPostProcessor实现类,
			//  并执行其postProcessBeanDefinitionRegistry方法
			boolean reiterate = true;
			while (reiterate) {
				reiterate = false;
				postProcessorNames = beanFactory.getBeanNamesForType(BeanDefinitionRegistryPostProcessor.class, true, false);
				for (String ppName : postProcessorNames) {
					// 过滤掉已经执行过的.
					if (!processedBeans.contains(ppName)) {
						currentRegistryProcessors.add(beanFactory.getBean(ppName, BeanDefinitionRegistryPostProcessor.class));
						processedBeans.add(ppName);
						// 如果有BeanDefinitionRegistryPostProcessor被执行,则有可能产生新的BeanDefinitionRegistryPostProcessor
						// 所以需要再次循环查找一次.
						reiterate = true;
					}
				}
				sortPostProcessors(currentRegistryProcessors, beanFactory);
				registryProcessors.addAll(currentRegistryProcessors);
				// 依次执行BeanDefinitionRegistryPostProcessor的postProcessBeanDefinitionRegistry()方法
				// 执行时机是加载bean定义之前
				invokeBeanDefinitionRegistryPostProcessors(currentRegistryProcessors, registry);
				currentRegistryProcessors.clear();
			}

			// 执行所有BeanDefinitionRegistryPostProcessor接口的postProcessBeanFactory方法
			// 加载bean定义之后.但是实例化bean实例之前
			invokeBeanFactoryPostProcessors(registryProcessors, beanFactory);

			// 执行所有普通的BeanFactoryPostProcessor的postProcessBeanFactory方法。这些BeanFactoryPostProcessor是从方法传进来的.
			invokeBeanFactoryPostProcessors(regularPostProcessors, beanFactory);
		}
    else {
			// Invoke factory processors registered with the context instance.
			invokeBeanFactoryPostProcessors(beanFactoryPostProcessors, beanFactory);
		}


		// 至此,上面的过程已经处理完了入参beanFactoryPostProcessors和容器中所有的BeanDefinitionRegistryPostProcessor
		///


		// 下面开始处理容器中的所有 BeanFactoryPostProcessor
		// Do not initialize FactoryBeans here: We need to leave all regular beans
		// uninitialized to let the bean factory post-processors apply to them!
		// 查找容器中所有实现了BeanFactoryPostProcessor接口的实现类
		String[] postProcessorNames =
				beanFactory.getBeanNamesForType(BeanFactoryPostProcessor.class, true, false);

		// Separate between BeanFactoryPostProcessors that implement PriorityOrdered,
		// Ordered, and the rest.
		// 用于存放所有实现了PriorityOrdered接口的BeanFactoryPostProcessor
		List<BeanFactoryPostProcessor> priorityOrderedPostProcessors = new ArrayList<>();
		// 用于存放实现了Ordered接口的BeanFactoryPostProcessor的beanName
		List<String> orderedPostProcessorNames = new ArrayList<>();
		// 用于实现了普通未实现Ordered接口的BeanFactoryPostProcessor的beanName
		List<String> nonOrderedPostProcessorNames = new ArrayList<>();
		// 循环所有的BeanFactoryPostProcessors
		for (String ppName : postProcessorNames) {
			// 如果前面已经执行过,直接跳过
			if (processedBeans.contains(ppName)) {
				// skip - already processed in first phase above
			}
			// 如果实现了PriorityOrdered接口,则获取bean并加入到priorityOrderedPostProcessors
			else if (beanFactory.isTypeMatch(ppName, PriorityOrdered.class)) {
				priorityOrderedPostProcessors.add(beanFactory.getBean(ppName, BeanFactoryPostProcessor.class));
			}
			// 如果是实现了Ordered接口的BeanFactoryPostProcessor,直接将其beanName放入到orderedPostProcessorNames
			else if (beanFactory.isTypeMatch(ppName, Ordered.class)) {
				orderedPostProcessorNames.add(ppName);
			}
			// 其他普通bean的名称放入到nonOrderedPostProcessorNames
			else {
				nonOrderedPostProcessorNames.add(ppName);
			}
		}

		// 对实现了PriorityOrdered接口的BeanFactoryPostProcessor进行排序
		sortPostProcessors(priorityOrderedPostProcessors, beanFactory);
		// 调用所有实现了PriorityOrdered接口的BeanFactoryPostProcessor的postProcessBeanFactory方法
		invokeBeanFactoryPostProcessors(priorityOrderedPostProcessors, beanFactory);

		// 获取所有实现了Ordered接口的BeanFactoryPostProcessor,并获取Bean实例,添加到orderedPostProcessors中,准备执行
		List<BeanFactoryPostProcessor> orderedPostProcessors = new ArrayList<>();
		for (String postProcessorName : orderedPostProcessorNames) {
			orderedPostProcessors.add(beanFactory.getBean(postProcessorName, BeanFactoryPostProcessor.class));
		}

		// 对orderedPostProcessors排序
		sortPostProcessors(orderedPostProcessors, beanFactory);
		// 调用实现了Ordered接口的BeanFactoryPostProcessor的postProcessBeanFactory方法
		invokeBeanFactoryPostProcessors(orderedPostProcessors, beanFactory);

		// 获取所有普通的未实现Ordered接口和PriorityOrdered接口的BeanFactoryPostProcessor对应的Bean实例,并添加到nonOrderedPostProcessors
		List<BeanFactoryPostProcessor> nonOrderedPostProcessors = new ArrayList<>();
		for (String postProcessorName : nonOrderedPostProcessorNames) {
			nonOrderedPostProcessors.add(beanFactory.getBean(postProcessorName, BeanFactoryPostProcessor.class));
		}

		// 执行剩余未实现Ordered接口和PriorityOrdered接口的BeanFactoryPostProcessor的postProcessBeanFactory方法.
		invokeBeanFactoryPostProcessors(nonOrderedPostProcessors, beanFactory);

		// Clear cached merged bean definitions since the post-processors might have
		// modified the original metadata, e.g. replacing placeholders in values...
		// 删除元数据(bean名称,bean定义等?)缓存,因为在执行后置处理器的过程中,原始的元数据可能已经被修改,例如:属性值中的占位符信息
		beanFactory.clearMetadataCache();
	}

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

		// 遍历所有实现了BeanFactoryPostProcessor接口的实现类,并调用实现类的postProcessBeanFactory方法.
		for (BeanFactoryPostProcessor postProcessor : postProcessors) {
			postProcessor.postProcessBeanFactory(beanFactory);
		}
	}

       其实大家看完上面的源码,其实后面的执行BeanPostProcessor的时候其实大家感觉是不是有点冗余,大家可以自己尝试改下源码,在获取实现Order接口跟没有实现order接口的时候大家可以直接去获取bean而不用多加两个集合然后后面再调用getBean.

        根据上面源码的流程图如下:

         好了,到此Spring的BeanPostProcessor的执行流程就讲到这里就结束了,这个时候有人问,那啥时候执行呢?这里我先给大家看一个东西,通过xml配置,如果我们如要开启注解那就需要加一个标签:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:msb="http://www.mashibing.com/schema/user"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/context  http://www.springframework.org/schema/context/spring-context.xsd
        http://www.mashibing.com/schema/user http://www.mashibing.com/schema/user.xsd">

    <context:component-scan base-package="com.mqc" ></context:component-scan>
</beans>

         我们之前讲过除了bean、beans、import、alias标签其实都是自定义标签,我们来看下他是如何来解析component-scan这个标签的。


/**
 * {@link org.springframework.beans.factory.xml.NamespaceHandler}
 * for the '{@code context}' namespace.
 *
 * @author Mark Fisher
 * @author Juergen Hoeller
 * @since 2.5
 *
 * 在Spring加载Bean定义时会执行该方法.解析标签定义
 */
public class ContextNamespaceHandler extends NamespaceHandlerSupport {

	@Override
	public void init() {
		// 解析properties配置文件中的key-value值
		registerBeanDefinitionParser("property-placeholder", new PropertyPlaceholderBeanDefinitionParser());
		registerBeanDefinitionParser("property-override", new PropertyOverrideBeanDefinitionParser());
		// 向容器中注册如下3个BeanPostProcessor:。
		//   注意:Sprint 4.2.7版本向容器注册的是4个BeanPostProcessor,其中还有另外一个RequiredAnnotationBeanPostProcessor
		/**
		 * AutowiredAnnotationBeanPostProcessor:
		 * CommonAnnotationBeanPostProcessor:
		 * PersistenceAnnotationBeanPostProcessor:
		 *   这4个BeanPostProcessor的作用,就是为了系统能够识别相应的注解
			 如果想使用@Resource 、@PostConstruct、@PreDestroy等注解就必须声明 CommonAnnotationBeanPostProcessor。
			 如果想使用@PersistenceContext注解,就必须声明 PersistenceAnnotationBeanPostProcessor的Bean。
			 如果想使用@Autowired注解,那么就必须事先在 Spring 容器中声明 AutowiredAnnotationBeanPostProcessor Bean。
			 如果想使用 @Required的注解,就必须声明 RequiredAnnotationBeanPostProcessor 的Bean。
		 */
		registerBeanDefinitionParser("annotation-config", new AnnotationConfigBeanDefinitionParser());
		registerBeanDefinitionParser("component-scan", new ComponentScanBeanDefinitionParser());
		registerBeanDefinitionParser("load-time-weaver", new LoadTimeWeaverBeanDefinitionParser());
		registerBeanDefinitionParser("spring-configured", new SpringConfiguredBeanDefinitionParser());
		registerBeanDefinitionParser("mbean-export", new MBeanExportBeanDefinitionParser());
		registerBeanDefinitionParser("mbean-server", new MBeanServerBeanDefinitionParser());
	}

}

        然后查看对应parse方法:

	@Override
	@Nullable
	public BeanDefinition parse(Element element, ParserContext parserContext) {
		// 获取<context:component-scan base-package=""/> 中base-package的属性值
		String basePackage = element.getAttribute(BASE_PACKAGE_ATTRIBUTE);

		// 这个属性值可能是一个占位符,也可能是一个或者多个逗号隔开的包路径,所以调用resolvePlaceholders进行占位符的解析
		basePackage = parserContext.getReaderContext().getEnvironment().resolvePlaceholders(basePackage);

		// 解析完成之后,将其转为数组。base-package可以使用分隔符隔开指定多个包扫描路径(,; \t\n)
		String[] basePackages = StringUtils.tokenizeToStringArray(basePackage,
				ConfigurableApplicationContext.CONFIG_LOCATION_DELIMITERS);

		// 创建bean定义扫描器Scanner
		ClassPathBeanDefinitionScanner scanner = configureScanner(parserContext, element);

		/**
		 * 使用类路径扫描器扫描指定包下的bean定义,将扫描到的bean定义注册到BeanDefinitionRegistry中,
		 *  然后将其封装为一个BeanDefinitionHolder集合返回
		 */
		Set<BeanDefinitionHolder> beanDefinitions = scanner.doScan(basePackages);

		// 注册一些后置处理器组件,例如:ContextAnnotationAutowireCandidateResolver或者ConfigurationClassPostProcesor等
		//   和new AnnotationConfigApplicationContext(config.class) 中注册的组件相同。用来在某些时机解析一些带特定注解的bean
		registerComponents(parserContext.getReaderContext(), beanDefinitions, element);

		return null;
	}

	protected void registerComponents(
			XmlReaderContext readerContext, Set<BeanDefinitionHolder> beanDefinitions, Element element) {

		Object source = readerContext.extractSource(element);

		// 这是一个组件的集合,将某个包下扫描到的组件全部保存在这个集合中。包括了组件的名称,描述,bean定义,引用等.
		CompositeComponentDefinition compositeDef = new CompositeComponentDefinition(element.getTagName(), source);

		for (BeanDefinitionHolder beanDefHolder : beanDefinitions) {
			compositeDef.addNestedComponent(new BeanComponentDefinition(beanDefHolder));
		}

		// <context:component-scan annotation-config="true" />
		boolean annotationConfig = true;

		// 解析annotation-config属性的值,默认为true。即:默认就会注册注解驱动相关的后置处理器.
		if (element.hasAttribute(ANNOTATION_CONFIG_ATTRIBUTE)) {
			annotationConfig = Boolean.parseBoolean(element.getAttribute(ANNOTATION_CONFIG_ATTRIBUTE));
		}

		// 开启注解驱动,xml中添加配置:<context:annotation-config /> 即可支持.
		if (annotationConfig) {
			// 给容器中注册默认的Spring后置处理器,包括用来处理各种注解及解析配置类的后置处理器.
			Set<BeanDefinitionHolder> processorDefinitions =
					AnnotationConfigUtils.registerAnnotationConfigProcessors(readerContext.getRegistry(), source);
			for (BeanDefinitionHolder processorDefinition : processorDefinitions) {
				compositeDef.addNestedComponent(new BeanComponentDefinition(processorDefinition));
			}
		}
		// 触发组件注册事件
		readerContext.fireComponentRegistered(compositeDef);
	}

public static Set<BeanDefinitionHolder> registerAnnotationConfigProcessors(
			BeanDefinitionRegistry registry, @Nullable Object source) {
		// 获取Bean工厂.默认为DefaultListableBeanFactory
		DefaultListableBeanFactory beanFactory = unwrapDefaultListableBeanFactory(registry);
		if (beanFactory != null) {
			if (!(beanFactory.getDependencyComparator() instanceof AnnotationAwareOrderComparator)) {
				// 设置默认的排序比较器,在执行Bean工厂的后置处理器时会用到,用来按照优先级来执行Bean工厂的后置处理器。
				// AnnotationAwareOrderComparator是OrderComparator的子类
				//  用来支持Spring的Ordered类、@Order注解和@Priority注解
				beanFactory.setDependencyComparator(AnnotationAwareOrderComparator.INSTANCE);
			}
			// beanFactory中的autowireCandidateResolver默认为:SimpleAutowireCandidateResolver
			if (!(beanFactory.getAutowireCandidateResolver() instanceof ContextAnnotationAutowireCandidateResolver)) {
				// 设置Bean工厂中bean自动注入时的候选解析器
				beanFactory.setAutowireCandidateResolver(new ContextAnnotationAutowireCandidateResolver());
			}
		}

		Set<BeanDefinitionHolder> beanDefs = new LinkedHashSet<>(8);

		// 判断Bean定义注册中心是否包含有名称为"org.springframework.context.annotation.internalConfigurationAnnotationProcessor"的Bean定义
		// 如果不包括,则创建类型为ConfigurationClassPostProcessor的Bean定义,并向Bean定义注册中心里面注册

		// 用途:ConfigurationClassPostProcessor后置处理器是用来处理@Configuration,@Import,@ImportResource和类内部的@Bean
		if (!registry.containsBeanDefinition(CONFIGURATION_ANNOTATION_PROCESSOR_BEAN_NAME)) {
			// 继承关系:
			// ConfigurationClassPostProcess --> BeanDefinitionRegistryPostProcessor --> BeanFactoryPostProcessor
			RootBeanDefinition def = new RootBeanDefinition(ConfigurationClassPostProcessor.class);
			def.setSource(source);
			// 将Bean定义放入到Bean定义注册中心的map中.
			beanDefs.add(registerPostProcessor(registry, def, CONFIGURATION_ANNOTATION_PROCESSOR_BEAN_NAME));
		}

		// 判断bean定义注册中心中是否包括名称为org.springframework.context.annotation.internalAutowiredAnnotationProcessor的Bean定义,
		// 如果不包括,向bean定义注册中心注册类型为AutowiredAnnotationBeanPostProcessor的Bean定义.

		// 用途:AutowiredAnnotationBeanPostProcessor后置处理器是用来处理@Autowired注解和@Value注解的
		if (!registry.containsBeanDefinition(AUTOWIRED_ANNOTATION_PROCESSOR_BEAN_NAME)) {
			// AutowireAnnotationBeanPostProcessor --> InstantiationAwareBeanPostProcessorAdapter
			// 		--> SmartInstantiationAwareBeanPostProcessor --> InstantiationAwareBeanPostProcessor --> BeanPostProcessor
			RootBeanDefinition def = new RootBeanDefinition(AutowiredAnnotationBeanPostProcessor.class);
			def.setSource(source);
			beanDefs.add(registerPostProcessor(registry, def, AUTOWIRED_ANNOTATION_PROCESSOR_BEAN_NAME));
		}

		// Check for JSR-250 support, and if present add the CommonAnnotationBeanPostProcessor.
		// 判断当前版本是否支持JSR-250
		// 然后判断bean定义注册中心中是否包括名称为org.springframework.context.annotation.internalCommonAnnotationProcessor的Bean定义,
		// 如果不包括,向bean定义注册中心注册类型为CommonAnnotationBeanPostProcessor的Bean定义.

		// 用途:CommonAnnotationBeanPostProcessor后置处理器提供对JSR-250规范注解的支持@javax.annotation.Resource、
		//    @javax.annotation.PostConstruct和@javax.annotation.PreDestroy等的支持。
		if (jsr250Present && !registry.containsBeanDefinition(COMMON_ANNOTATION_PROCESSOR_BEAN_NAME)) {
			// CommonAnnotationBeanPostProcessor --> InitDestroyAnnotationBeanPostProcessor(class) --> DestructionAwareBeanPostProcessor,MergedBeanDefinitionPostProcessor
			//			--> InstantiationAwareBeanPostProcessor --> BeanPostProcessor
			RootBeanDefinition def = new RootBeanDefinition(CommonAnnotationBeanPostProcessor.class);
			def.setSource(source);
			beanDefs.add(registerPostProcessor(registry, def, COMMON_ANNOTATION_PROCESSOR_BEAN_NAME));
		}

		// Check for JPA support, and if present add the PersistenceAnnotationBeanPostProcessor.
		// 判断是否支持JPA
		// 然后判断bean定义注册中心中是否包括名称为org.springframework.context.annotation.internalPersistenceAnnotationProcessor的Bean定义,
		// 如果不包括,向bean定义注册中心注册类型为PersistenceAnnotationBeanPostProcessor的Bean定义.

		//  用途:EventListenerMethodProcessor后置处理器提供@PersistenceContext的支持。
		if (jpaPresent && !registry.containsBeanDefinition(PERSISTENCE_ANNOTATION_PROCESSOR_BEAN_NAME)) {
			RootBeanDefinition def = new RootBeanDefinition();
			try {
				def.setBeanClass(ClassUtils.forName(PERSISTENCE_ANNOTATION_PROCESSOR_CLASS_NAME,
						AnnotationConfigUtils.class.getClassLoader()));
			}
			catch (ClassNotFoundException ex) {
				throw new IllegalStateException(
						"Cannot load optional framework class: " + PERSISTENCE_ANNOTATION_PROCESSOR_CLASS_NAME, ex);
			}
			def.setSource(source);
			beanDefs.add(registerPostProcessor(registry, def, PERSISTENCE_ANNOTATION_PROCESSOR_BEAN_NAME));
		}

		// 判断bean定义注册中心中是否包括名称为org.springframework.context.event.internalEventListenerProcessor的Bean定义,
		// 如果不包括,向bean定义注册中心注册类型为EventListenerMethodProcessor的Bean定义.
		if (!registry.containsBeanDefinition(EVENT_LISTENER_PROCESSOR_BEAN_NAME)) {
			RootBeanDefinition def = new RootBeanDefinition(EventListenerMethodProcessor.class);
			def.setSource(source);
			beanDefs.add(registerPostProcessor(registry, def, EVENT_LISTENER_PROCESSOR_BEAN_NAME));
		}

		// 判断bean定义注册中心中是否包括名称为org.springframework.context.event.internalEventListenerFactory的Bean定义,
		// 如果不包括,向bean定义注册中心注册类型为DefaultEventListenerFactory的Bean定义.

		// 用途:EventListenerMethodProcessor后置处理器提供对@EventListener注解的支持。
		//  @EventListener是在spring4.2之后出现的,可以在一个Bean的方法上使用@EventListener注解来自动注册一个ApplicationListener。
		if (!registry.containsBeanDefinition(EVENT_LISTENER_FACTORY_BEAN_NAME)) {
			RootBeanDefinition def = new RootBeanDefinition(DefaultEventListenerFactory.class);
			def.setSource(source);
			beanDefs.add(registerPostProcessor(registry, def, EVENT_LISTENER_FACTORY_BEAN_NAME));
		}

		return beanDefs;
	}

        可以看得到这里给我们的Spring容器中注入了org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor也就是ConfigurationClassPostProcessor等其他bean,那这个ConfigurationClassPostProcessor的主要作用是什么呢?这BFPP在Spring中的作用十分巨大,我们在下一篇博客中具体介绍这个ConfigurationClassPostProcessor的作用。

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值