其他分享
首页 > 其他分享> > 【spring】深入了解spring的PostProcessors

【spring】深入了解spring的PostProcessors

作者:互联网

PostProcessors简单介绍

BeanPostProcessor常用的有什么

BeanFactoryPostProcessor执行顺序:先执行注册,后执行处理

registerBeanPostProcessors源码分析

/**
 * 源码位于:org.springframework.context.support.AbstractApplicationContext.registerBeanPostProcessors(ConfigurableListableBeanFactory)
 * 将扫描到的BeanPostProcessors实例化并排序,并添加到BeanFactory的beanPostProcessors属性中去。
 * 在掉用这个方法之前会在加载reader的时候配置(这里生成BeanDefinition放入Bean工厂的BeanDefinitinoMap属性):new RootBeanDefinition(AutowiredAnnotationBeanPostProcessor.class);
 * 在掉用这个方法之前会在加载reader的时候配置(这里生成BeanDefinition放入Bean工厂的BeanDefinitinoMap属性):new RootBeanDefinition(CommonAnnotationBeanPostProcessor.class);
 * 在掉用这个方法之前会在prepareBeanFactory的时候配置(这里会加入到List<BeanPostProcessor> beanPostProcessors这个变量中):beanFactory.addBeanPostProcessor(new ApplicationContextAwareProcessor(this));
 * 在掉用这个方法之前会在prepareBeanFactory的时候配置(这里会加入到List<BeanPostProcessor> beanPostProcessors这个变量中):beanFactory.addBeanPostProcessor(new ApplicationListenerDetector(this));
 */
protected void registerBeanPostProcessors(ConfigurableListableBeanFactory beanFactory) {
	PostProcessorRegistrationDelegate.registerBeanPostProcessors(beanFactory, this);
}

/**
 * 具体的注册BeanPostProcessor方法
 */
public static void registerBeanPostProcessors(
		ConfigurableListableBeanFactory beanFactory, AbstractApplicationContext applicationContext) {

	// 拿到所有的BeanPostProcessor的子类
	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.
	// beanProcessorTargetCount表示BeanFactory中所有的BeanPostProcessor数量,+1表示BeanPostProcessorChecker
	int beanProcessorTargetCount = beanFactory.getBeanPostProcessorCount() + 1 + postProcessorNames.length;
	beanFactory.addBeanPostProcessor(new BeanPostProcessorChecker(beanFactory, beanProcessorTargetCount));

	// Separate between BeanPostProcessors that implement PriorityOrdered,
	// Ordered, and the rest.
	// 将不同类型的BeanPostProcessor进行分类
	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.
	// 升序排序,执行BeanFactory中实现了PriorityOrdered接口的BeanPostProcessor的addBeanPostProcessor()方法,添加到beanPostProcessors变量中
	sortPostProcessors(priorityOrderedPostProcessors, beanFactory);
	registerBeanPostProcessors(beanFactory, priorityOrderedPostProcessors);

	// Next, register the BeanPostProcessors that implement Ordered.
	// 实现了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);
		}
	}
	// 升序排序,执行BeanFactory中实现了Ordered接口的BeanPostProcessor的addBeanPostProcessor()方法,添加到beanPostProcessors变量中
	sortPostProcessors(orderedPostProcessors, beanFactory);
	registerBeanPostProcessors(beanFactory, orderedPostProcessors);

	// Now, register all regular BeanPostProcessors.
	// 其他的BeanPostProcessor处理
	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);
		}
	}
	// 执行BeanFactory中实现了Ordered接口的BeanPostProcessor的addBeanPostProcessor()方法,添加到beanPostProcessors变量中
	registerBeanPostProcessors(beanFactory, nonOrderedPostProcessors);

	// Finally, re-register all internal BeanPostProcessors.
	// MergedBeanDefinitionPostProcessor排在最后,这里可以理解为spring内部的BeanPostProcessor排在最后
	// 执行BeanFactory中实现了MergedBeanDefinitionPostProcessor接口的BeanPostProcessor的addBeanPostProcessor()方法,添加到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).
	// ApplicationListenerDetector放在所有BeanPostProcessor之后,注意ApplicationListenerDetector的equals()方法实现
	beanFactory.addBeanPostProcessor(new ApplicationListenerDetector(applicationContext));
}

invokeBeanFactoryPostProcessors源码分析

/**
 * 源码位于:org.springframework.context.support.AbstractApplicationContext.invokeBeanFactoryPostProcessors(ConfigurableListableBeanFactory)
 * 在掉用这个方法之前会在加载reader的时候配置(这里生成BeanDefinition放入Bean工厂的BeanDefinitinoMap属性):new RootBeanDefinition(ConfigurationClassPostProcessor.class);
 * 在掉用这个方法之前会在加载reader的时候配置:beanFactory.setDependencyComparator(AnnotationAwareOrderComparator.INSTANCE);
 */
protected void invokeBeanFactoryPostProcessors(ConfigurableListableBeanFactory beanFactory) {

	// 有顺序的执行BeanFactoryPostProcessors的方法
	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)
	// LoadTimeWeaver相关。
	if (!NativeDetector.inNativeImage() && beanFactory.getTempClassLoader() == null && beanFactory.containsBean(LOAD_TIME_WEAVER_BEAN_NAME)) {
		beanFactory.addBeanPostProcessor(new LoadTimeWeaverAwareProcessor(beanFactory));
		beanFactory.setTempClassLoader(new ContextTypeMatchClassLoader(beanFactory.getBeanClassLoader()));
	}
}

/**
 * BeanFactoryPostProcessors按入场方式分为:
 * 1. 程序员调用ApplicationContext的API手动添加
 * 2. Spring自己扫描出来的
 *
 * BeanFactoryPostProcessor按类型又可以分为:
 * 1. 普通BeanFactoryPostProcessor
 * 2. BeanDefinitionRegistryPostProcessor
 *
 * 执行顺序顺序如下:
 * 1. 执行手动添加的BeanDefinitionRegistryPostProcessor                       的postProcessBeanDefinitionRegistry()方法
 * 2. 执行扫描出来的BeanDefinitionRegistryPostProcessor(实现了PriorityOrdered)的postProcessBeanDefinitionRegistry()方法
 * 3. 执行扫描出来的BeanDefinitionRegistryPostProcessor(实现了Ordered)		   的postProcessBeanDefinitionRegistry()方法
 * 4. 执行扫描出来的BeanDefinitionRegistryPostProcessor(普通)				   的postProcessBeanDefinitionRegistry()方法
 * 5. 执行扫描出来的BeanDefinitionRegistryPostProcessor(所有)				   的postProcessBeanFactory()方法
 * 6. 执行手动添加的BeanFactoryPostProcessor								   的postProcessBeanFactory()方法
 * 7. 执行扫描出来的BeanFactoryPostProcessor(实现了PriorityOrdered)		   的postProcessBeanFactory()方法
 * 8. 执行扫描出来的BeanFactoryPostProcessor(实现了Ordered)		   		   的postProcessBeanFactory()方法
 * 9. 执行扫描出来的BeanFactoryPostProcessor(普通)				   		   的postProcessBeanFactory()方法
 *
 * ConfigurationClassPostProcessor就会在第2步执行,会进行扫描
 * 
 * beanFactory:是他的Bean工厂
 * beanFactoryPostProcessors:可能有BeanFactoryPostProcessor、BeanDefinitionRegistryPostProcessor
 */
public static void invokeBeanFactoryPostProcessors(
		ConfigurableListableBeanFactory beanFactory, List<BeanFactoryPostProcessor> beanFactoryPostProcessors) {

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

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

		// beanFactoryPostProcessors集合一般情况下都是空的,除非我们手动调用容器的addBeanFactoryPostProcessor方法添加了
		// beanFactoryPostProcessors中可能包含了:普通BeanFactoryPostProcessor对象和BeanDefinitionRegistryPostProcessor对象
		// 对于BeanDefinitionRegistryPostProcessor对象,会执行自己的postProcessBeanDefinitionRegistry()方法
		for (BeanFactoryPostProcessor postProcessor : beanFactoryPostProcessors) {
			// 存在beanFactoryPostProcessors,会进行分类确定是子接口还是当前的
			if (postProcessor instanceof BeanDefinitionRegistryPostProcessor) {
				BeanDefinitionRegistryPostProcessor registryProcessor =
						(BeanDefinitionRegistryPostProcessor) postProcessor;
				// 是子类的话,先调用注册的方法。
				// 执行通过ApplicationContext添加进来的BeanDefinitionRegistryPostProcessor的postProcessBeanDefinitionRegistry()方法
				registryProcessor.postProcessBeanDefinitionRegistry(registry);
				// 添加到registryProcessors
				registryProcessors.add(registryProcessor);
			}
			else {
				// 当前类是父类,不进行任何代码的执行,直接添加到regularPostProcessors
				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

		// First, invoke the BeanDefinitionRegistryPostProcessors that implement PriorityOrdered.
		// 首次进来只会拿到ConfigurableListableBeanFactory
		String[] postProcessorNames =
				beanFactory.getBeanNamesForType(BeanDefinitionRegistryPostProcessor.class, true, false);
		for (String ppName : postProcessorNames) {
			// 它实现了PriorityOrdered接口的时候,才会真正的创建Bean
			if (beanFactory.isTypeMatch(ppName, PriorityOrdered.class)) {
				currentRegistryProcessors.add(beanFactory.getBean(ppName, BeanDefinitionRegistryPostProcessor.class));
				processedBeans.add(ppName);
			}
		}
		// 升序排序,使用PriorityOrdered的getOrder进行比较
		sortPostProcessors(currentRegistryProcessors, beanFactory);
		registryProcessors.addAll(currentRegistryProcessors);
		// 执行刚刚找到的BeanDefinitionRegistryPostProcessor的postProcessBeanDefinitionRegistry方法。
		// 执行BeanFactory中实现了PriorityOrdered接口的BeanDefinitionRegistryPostProcessor的postProcessBeanDefinitionRegistry()方法
		// ConfigurableListableBeanFactory的postProcessBeanDefinitionRegistry内部会进行扫描!
		invokeBeanDefinitionRegistryPostProcessors(currentRegistryProcessors, registry, beanFactory.getApplicationStartup());
		currentRegistryProcessors.clear();

		// Next, invoke the BeanDefinitionRegistryPostProcessors that implement Ordered.
		// 继续来获取实现了BeanDefinitionRegistryPostProcessor的类,进过来扫描,这里可以发现程序员自定义的Bean
		postProcessorNames = beanFactory.getBeanNamesForType(BeanDefinitionRegistryPostProcessor.class, true, false);
		for (String ppName : postProcessorNames) {
			// processedBeans表示该beanFactoryPostProcessor的postProcessBeanDefinitionRegistry()方法已经执行过了,不再重复执行
			// 简单理解就是过滤掉之前已经执行过的,准备去执行实现Ordered接口的。
			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接口并且实现了Ordered接口的postProcessBeanDefinitionRegistry方法
		//  执行BeanFactory中实现了Ordered接口的BeanDefinitionRegistryPostProcessor的postProcessBeanDefinitionRegistry()方法
		invokeBeanDefinitionRegistryPostProcessors(currentRegistryProcessors, registry, beanFactory.getApplicationStartup());
		currentRegistryProcessors.clear();

		// Finally, invoke all other BeanDefinitionRegistryPostProcessors until no further ones appear.
		// 执行哪些没有实现了PriorityOrdered或Ordered接口的普通BeanDefinitionRegistryPostProcessor的postProcessBeanDefinitionRegistry()方法
		// 在这个过程中可能会向BeanFactory中注册另外的BeanDefinitionRegistryPostProcessor,所以需要while,直到确定所有的BeanDefinitionRegistryPostProcessor都执行完了
		// 在这个过程中注册的BeanDefinitionRegistryPostProcessor,所实现的PriorityOrdered或Ordered接口可能会不按顺序执行
		// 比如 A注册了B和C,B又注册了D和E,那么B和C会按顺序执行,D和E也会按顺序执行,但是B、C、D、E整体不能保证是顺序执行
		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);
					reiterate = true;
				}
			}
			sortPostProcessors(currentRegistryProcessors, beanFactory);
			registryProcessors.addAll(currentRegistryProcessors);
			invokeBeanDefinitionRegistryPostProcessors(currentRegistryProcessors, registry, beanFactory.getApplicationStartup());
			currentRegistryProcessors.clear();
		}

		// Now, invoke the postProcessBeanFactory callback of all processors handled so far.
		// 执行完BeanDefinitionRegistryPostProcessor的postProcessBeanDefinitionRegistry()方法后,
		// 再执行BeanDefinitionRegistryPostProcessor的postProcessBeanFactory()方法
		invokeBeanFactoryPostProcessors(registryProcessors, beanFactory);

		// 执行手动添加的普通BeanFactoryPostProcessor的postProcessBeanFactory()方法
		invokeBeanFactoryPostProcessors(regularPostProcessors, beanFactory);
	}

	else {
		// Invoke factory processors registered with the context instance.
		// 没有子类,直接执行BeanFactoryPostProcessor的postProcessBeanFactory()方法
		invokeBeanFactoryPostProcessors(beanFactoryPostProcessors, beanFactory);
	}

	// 代码执到这里,就不会出现新的BeanDefinition!
	
	// 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.
	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.
	// 排序执行BeanFactory中实现了PriorityOrdered接口的BeanFactoryPostProcessor的postProcessBeanFactory()方法
	sortPostProcessors(priorityOrderedPostProcessors, beanFactory);
	invokeBeanFactoryPostProcessors(priorityOrderedPostProcessors, beanFactory);

	// Next, invoke the BeanFactoryPostProcessors that implement Ordered.
	// 排序执行BeanFactory中实现了Ordered接口的BeanFactoryPostProcessor的postProcessBeanFactory()方法
	List<BeanFactoryPostProcessor> orderedPostProcessors = new ArrayList<>(orderedPostProcessorNames.size());
	for (String postProcessorName : orderedPostProcessorNames) {
		orderedPostProcessors.add(beanFactory.getBean(postProcessorName, BeanFactoryPostProcessor.class));
	}
	sortPostProcessors(orderedPostProcessors, beanFactory);
	invokeBeanFactoryPostProcessors(orderedPostProcessors, beanFactory);

	// Finally, invoke all other BeanFactoryPostProcessors.
	// 排序执行BeanFactory中其他的BeanFactoryPostProcessor的postProcessBeanFactory()方法
	List<BeanFactoryPostProcessor> nonOrderedPostProcessors = new ArrayList<>(nonOrderedPostProcessorNames.size());
	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();
}

结束语

标签:ppName,spring,beanFactory,BeanFactoryPostProcessor,PostProcessors,深入,BeanDefinit
来源: https://blog.csdn.net/qq_35436158/article/details/123193500