Spring实例化源码解析之BeanFacotryPostProcessor和BeanDefinitionRegistryPostProcessor(一)

news2024/9/30 9:23:37

invokeBeanFactoryPostProcessors

前言

AbstractApplicationContext类的refresh方法是spring实例化流程的开始。本章主要是介绍invokeBeanFactoryPostProcessors(beanFactory)方法,对其内部源码进行详细分析。接下来就来看看这句简单的代码后面具体做了什么。Spring源码版本6.0.12,代码版本不同可能代码会稍有不同,但是核心逻辑大差不差。

分析前的准备

接下来就直接从代码开始进行源码分析。源码的分析将会非常枯燥、并且常看常新。本章除了记录自己的源码学习内容,也希望能给大家带来帮助。

spring启动main方法,在调用refresh之前会register(AopConfig.class),这个是前提。

public static void main(String[] args) {
		AnnotationConfigApplicationContext annotationConfigApplicationContext =
				new AnnotationConfigApplicationContext(AopConfig.class);
				}

AopConfig类其实可以是任意类,我只是为了加上@ComponentScan注解

@EnableAspectJAutoProxy
@ComponentScan(value = {"com.qhyu.cloud.**"})
public class AopConfig {

}

invokeBeanFactoryPostProcessors

Instantiate and invoke all registered BeanFactoryPostProcessor beans,respecting explicit order if given.

实例化并调用所有已注册的 BeanFactoryPostProcessor beans,如果给定的话,请遵守显式顺序。次方法就在AbstractApplicationContext中。

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 (!NativeDetector.inNativeImage() && beanFactory.getTempClassLoader() == null && beanFactory.containsBean(LOAD_TIME_WEAVER_BEAN_NAME)) {
			beanFactory.addBeanPostProcessor(new LoadTimeWeaverAwareProcessor(beanFactory));
			beanFactory.setTempClassLoader(new ContextTypeMatchClassLoader(beanFactory.getBeanClassLoader()));
		}
	}

PostProcessorRegistrationDelegate.invokeBeanFactoryPostProcessors(beanFactory, getBeanFactoryPostProcessors())是核心的方法,本以为getBeanFactoryPostProcessors()方法会获取到所有的BeanFactoryPostProcessors,毕竟看起来名字很像,但是打断点发现其实此处返回的List size为0。

那么接下来就直接查看invokeBeanFactoryPostProcessors(beanFactory, getBeanFactoryPostProcessors())方法。

BeanFactoryPostProcessor

在spring的实例化过程中我们可以经常看到BeanFactoryPostProcessor接口,几乎充斥着整个实例化过程。BeanDefinitionRegistryPostProcessor也是spring框架中一个比较重要的接口。因为BeanDefinitionRegistryPostProcessor继承了BeanFactoryPostProcessor,所以就放一起来讲解了。

  • BeanFacotryPostProcessor

BeanFactoryPostProcessor是一个接口,用于在Spring容器实例化任何Bean之前修改BeanDefinition(Bean定义)或配置的后置处理器,它允许对BeanDefinition进行修改、添加自定义属性甚至可以完全替换beanDefinition。

关键点:

1、在spring容器加载BeanDefinition后,但在实例化Bean之前调用。

2、用于修改BeanDefinition的元数据(如类名、作用域、属性等)。

3、对所有的BeanDefinition生效,包括非延迟加载和延迟加载的bean。

4、可以通过实现BeanFactoryPostProcessor接口并注册为Spring容器的Bean来自定义处理逻辑。

示例:

public class CustomBeanFactoryPostProcessor implements BeanFactoryPostProcessor {
    @Override
    public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {
        // 在这里进行Bean定义的修改或自定义处理逻辑
    }
}
  • BeanDefinitionRegistryPostProcessor

BeanDefinitionRegistryPostProcessor是BeanFacotryPostProcessor的子接口,用于在Spring容器实例化任何Bean之前修改Bean定义的后置处理器。与BeanFacotryPostProcessor相比,它提供了更广泛的功能,包括添加、修改和删除Bean定义。

关键点:

1、继承自BeanFactoryPostProcessor接口,扩展了修改Bean定义的功能。

2、在Spring容器加载Bean定义后,但在实例化Bean之前调用。

3、用于直接操作Bean定义的注册表,可以添加、修改和删除Bean定义。

4、可以通过实现BeanDefinitionRegistryPostProcessor接口并注册为Spring容器的Bean来自定义处理逻辑。

示例:

public class CustomBeanDefinitionRegistryPostProcessor implements BeanDefinitionRegistryPostProcessor {
    @Override
    public void postProcessBeanDefinitionRegistry(BeanDefinitionRegistry registry) throws BeansException {
        // 在这里进行Bean定义的添加、修改或删除操作
    }

    @Override
    public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {
        // 可以不实现该方法,或者在这里进行其他的BeanFactoryPostProcessor的处理逻辑
    }
}

关系和使用区别:

  • BeanDefinitionRegistryPostProcessor是BeanFactoryPostProcessor的子接口,它们都用于在实例化Bean之前修改Bean定义。
  • BeanDefinitionRegistryPostProcessor在功能上更加强大,可以添加、修改和删除Bean定义,而BeanFactoryPostProcessor只能修改Bean定义的元数据。
  • BeanDefinitionRegistryPostProcessor在处理Bean定义之前,会先回调BeanFactoryPostProcessor的方法,因此它们可以一起使用,但是顺序上有所区别。
  • BeanDefinitionRegistryPostProcessor可以直接操作Bean定义注册表,而BeanFactoryPostProcessor只能通过ConfigurableListableBeanFactory来间接操作Bean定义。
  • 通常情况下,更常用的是实现BeanFactoryPostProcessor接口,而BeanDefinitionRegistryPostProcessor在特定需求下使用,例如需要动态地添加或修改Bean定义。

PostProcessorRegistrationDelegate.invokeBeanFactoryPostProcessors

这里引入了一个新的类PostProcessorRegistrationDelegate。

invokeBeanFactoryPostProcessors方法的参数解释如下:

参数1:默认是DefaultListableBeanFactory,实现了BeanDefinitionRegistry

参数2:一般情况下为空,除非调用Spring容器的refresh方法之前调用API手动添加了BeanFactoryPostProcessor

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

		// 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

		// Invoke BeanDefinitionRegistryPostProcessors first, if any.
		// 如果有的话,首先调用 BeanDefinitionRegistryPostProcessors
		// 存放处理完毕的bfpp名称
		Set<String> processedBeans = new HashSet<>();

		// 因为默认传的DefaultListableBeanFactory==beanFactory实现了BeanDefinitionRegistry接口,所以进入if的逻辑
		if (beanFactory instanceof BeanDefinitionRegistry) {
			// 也就是说这个if里面要使用的就是BeanDefinitionRegistry的特性。
			BeanDefinitionRegistry registry = (BeanDefinitionRegistry) beanFactory;
			// regular常规的意思
			// regularPostProcessors记录通过硬编码方式注册的BeanFactoryPostProcessor类型的处理器
			// 存放直接实现了BeanFactoryPostProcessor接口的实现类集合,bfpp的作用是可以定制化修改bd
			List<BeanFactoryPostProcessor> regularPostProcessors = new ArrayList<>();

			// registryProcessors记录通过硬编码方式注册是BeanDefinitionRegistryPostProcessor
			// 存放直接实现了BeanDefinitionRegistryPostProcessor接口实现类的集合,brpp可以定制化修改bd
			List<BeanDefinitionRegistryPostProcessor> registryProcessors = new ArrayList<>();

			// 除非手动注入bfpp 否则这个for循环没有什么意义,也就是AnnotationConfigApplicationContext.addBeanFactoryPostProcessor
			// 此处可以作为扩展。AnnotationConfigApplicationContext.addBeanFactoryPostProcessor
			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.

			// currentRegistryProcessors记录通过配置方式注册的BeanDefinitionRegistryPostProcessor类型的处理器
			// 用于存放当前即将执行BeanDefinitionRegistryPostProcessor实现类
			List<BeanDefinitionRegistryPostProcessor> currentRegistryProcessors = new ArrayList<>();

			// First, invoke the BeanDefinitionRegistryPostProcessors that implement PriorityOrdered.
			// 第一次调用:首先调用实现了排序的BeanDefinitionRegistryPostProcessors

			// 这里这个方法多次调用返回不同的值是因为beanFactory中的BeanDefinitionRegistryPostProcessors的新增,一开始都想不明白。
			// 其实最主要的就是第一次执行了invokeBeanDefinitionRegistryPostProcessor方法
			// 真实逻辑就是ConfigurationClassPostProcessor的postProcessBeanDefinitionRegistry方法,
			// 这里会根据我们的AopConfig,也就是@ComponentScan注解的path来扫描我们自己的类,并且生产BeanDefiniton信息
			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);
				}
			}
			// 很明显 这里是排序,先不进去看,因为此时currentRegistryProcessors只有一个ConfigurationClassPostProcessor
			sortPostProcessors(currentRegistryProcessors, beanFactory);

			registryProcessors.addAll(currentRegistryProcessors);
			// 这个方法就是核心内容,我这个工程使用了AOPConfig启动类,也就是说一开始会解析这个类,包含类上的ComponentScan注解,会把路径下的东西用ClassPathBeanDefinitionScanner来扫描出来
			// 生成beanDefinition放入BeanFactory(DefaultListableBeanFactory),所以第二次调用的时候就可以扫描出其他的BeanFactoryPostProcessors
			// ConfigurationClassPostProcessor ==  currentRegistryProcessors
			invokeBeanDefinitionRegistryPostProcessors(currentRegistryProcessors, registry, beanFactory.getApplicationStartup());
			// 清空当前注册的BeanDefinitionRegistryPostProcessors
			currentRegistryProcessors.clear();

			// Next, invoke the BeanDefinitionRegistryPostProcessors that implement Ordered.
			// 接下来,调用实现 Ordered 的 BeanDefinitionRegistryPostProcessors。
			// 第二次调用:这个时候已经获取了ComponentScan注解中的路径下的BeanDefinition了。
			// 所以会把我们定义的BeanDefinitionRegistryPostProcessor加载起来,或者第三方框架实现的BeanDefinitionRegistryPostProcessor加载
			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);
				}
			}
			// 排序,看一下排序的规则是什么?,我可以实现Ordered接口PriorityOrdered接口或者注解
			sortPostProcessors(currentRegistryProcessors, beanFactory);
			registryProcessors.addAll(currentRegistryProcessors);
			// 调用了currentRegistryProcessors中的BeanDefinitionRegistryPostProcessors--》postProcessBeanDefinitionRegistry方法
			// 因为BeanDefinitionRegistryPostProcessor的职责就是加载Bean的BeanDefinition,后续才好加载这个bean,至于要修改的话,交给BeanFactoryPostProcessor
			invokeBeanDefinitionRegistryPostProcessors(currentRegistryProcessors, registry, beanFactory.getApplicationStartup());
			currentRegistryProcessors.clear();

			// Finally, invoke all other BeanDefinitionRegistryPostProcessors until no further ones appear.
			// 最后,调用所有其他 BeanDefinitionRegistryPostProcessors 直到不再出现。
			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.
			invokeBeanFactoryPostProcessors(registryProcessors, beanFactory);
			invokeBeanFactoryPostProcessors(regularPostProcessors, beanFactory);
		}

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

		/** =============下面就是处理BeanFactoryPostProcessor的实现类=============  */
		// Do not initialize FactoryBeans here: We need to leave all regular beans
		// uninitialized to let the bean factory post-processors apply to them!
		// 获取bfpp接口实现类
		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(priorityOrderedPostProcessors, beanFactory);
		invokeBeanFactoryPostProcessors(priorityOrderedPostProcessors, beanFactory);

		// Next, invoke the BeanFactoryPostProcessors that implement Ordered.
		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.
		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();
	}

我们今天要分析的源码就是上面这一个方法,在源码分析的时候我们还是要稍微读一读方法名称和各个单词,因为在spring中我们很多时候都可以通过方法名称来判断出要做的事情,因为源码分析打断点的时候如果一直往下看可能就出不来了。所以有的时候需要我们智能的跳过一些个方法。

beanFactory

在进入到方法之前我们先看下beanFactory,这个beanFactory我感觉可以理解为bean工厂。beanfactory是spring框架中的一个核心接口,它提供了一种机制来管理和访问程序中的对象(也称为Bean)。在spring中,对象的创建、配置和管理是由beanfactory负责的。

首先可以知道传入的是DefaultListableBeanFactory,所以说beanFactory instanceof BeanDefinitionRegistry是true。会进入到if逻辑中。

其次当前beanFactory中已经注册了5个beanDefinition。aopConfig就不多说了,在调用refresh方法之前手动注册的,其他四个可以先不管。

在这里插入图片描述

源码分析

接下来会集中拆解PostProcessorRegistrationDelegate类中的invokeBeanFactoryPostProcessors方法来逐步分析源码。

public static void invokeBeanFactoryPostProcessors(
			ConfigurableListableBeanFactory beanFactory, List<BeanFactoryPostProcessor> beanFactoryPostProcessors) {
		Set<String> processedBeans = new HashSet<>();
		// 因为默认传的DefaultListableBeanFactory==beanFactory实现了BeanDefinitionRegistry接口,所以进入if的逻辑
		if (beanFactory instanceof BeanDefinitionRegistry) {
			// 也就是说这个if里面要使用的就是BeanDefinitionRegistry的特性。或者作为参数传递固定了类型。
			BeanDefinitionRegistry registry = (BeanDefinitionRegistry) beanFactory;
			// regular常规的意思
			// regularPostProcessors记录通过硬编码方式注册的BeanFactoryPostProcessor类型的处理器
			// 存放直接实现了BeanFactoryPostProcessor接口的实现类集合,bfpp的作用是可以定制化修改bd
			List<BeanFactoryPostProcessor> regularPostProcessors = new ArrayList<>();

			// registryProcessors记录通过硬编码方式注册是BeanDefinitionRegistryPostProcessor
			// 存放直接实现了BeanDefinitionRegistryPostProcessor接口实现类的集合,brpp可以定制化修改bd
			List<BeanDefinitionRegistryPostProcessor> registryProcessors = new ArrayList<>();	

processedBeans根据是用来存放String的集合,根据processedBeans.add方法可以知道存放的是处理完成的BeanDefinitionRegistryPostProcessor的名称。

regularPostProcessors存放的是BeanFacotyPostProcessor。

registryProcessors存放的是BeanDefinitionRegistryPostProcessor。

接下来拆解这个for循环,beanFactoryPostProcessors参数size=0,所以当前这个for循环肯定是不会执行的。然而整个invokeBeanFactoryPostProcessors方法中只有这个for循环中有使用regularPostProcessors.add方法。所以regular相关的后续遇到了可以先跳过。

此处可以作为一个扩展点。AnnotationConfigApplicationContext.addBeanFactoryPostProcessor可以让for循环生效。也就是手动注入beanFactoryPostProcessor,在这篇文章就不深入了。

for (BeanFactoryPostProcessor postProcessor : beanFactoryPostProcessors) {
				if (postProcessor instanceof BeanDefinitionRegistryPostProcessor) {
					BeanDefinitionRegistryPostProcessor registryProcessor =
							(BeanDefinitionRegistryPostProcessor) postProcessor;
					registryProcessor.postProcessBeanDefinitionRegistry(registry);
					registryProcessors.add(registryProcessor);
				}
				else {
					regularPostProcessors.add(postProcessor);
				}
			}
// 用于存放当前即将执行BeanDefinitionRegistryPostProcessor实现类
List<BeanDefinitionRegistryPostProcessor> currentRegistryProcessors = new ArrayList<>();

第一次调用实现了ProrityOrdered的BeanDefinitionRegistryPostProcessors逻辑,接下来将是最重要的部分了。

		// First, invoke the BeanDefinitionRegistryPostProcessors that implement PriorityOrdered.
			
			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);
				}
			}
			// 很明显 这里是排序,先不进去看,因为此时currentRegistryProcessors只有一个ConfigurationClassPostProcessor
			sortPostProcessors(currentRegistryProcessors, beanFactory);

			registryProcessors.addAll(currentRegistryProcessors);
			// 这个方法就是核心内容,我这个工程使用了AOPConfig启动类,也就是说一开始会解析这个类,包含类上的ComponentScan注解,会把路径下的东西用ClassPathBeanDefinitionScanner来扫描出来
			// 生成beanDefinition放入BeanFactory(DefaultListableBeanFactory),所以第二次调用的时候就可以扫描出其他的BeanFactoryPostProcessors
			// ConfigurationClassPostProcessor ==  currentRegistryProcessors
			invokeBeanDefinitionRegistryPostProcessors(currentRegistryProcessors, registry, beanFactory.getApplicationStartup());
			// 清空当前注册的BeanDefinitionRegistryPostProcessors
			currentRegistryProcessors.clear();

首先查看postProcessorNames会返回什么东西。

在这里插入图片描述

org.springframework.context.annotation.internalConfigurationAnnotationProcessor 这个有点印象。可以回到开始的beanFactory的截图中找到。beanDefinitonNames中第一个记录就是这个名称。

也就是说beanFactory.getBeanNamesForType方法是从spring的beanFactory中的beanDefinitionMap中去找有没有符合类型为BeanDefinitionRegistryPostProcessor的类,并且如果实现了PriorityOrdered.class就把这个BeanDefinitionRegistryPostProcessor加入到currentRegistryProcessors和processedBeans集合中。

在这里插入图片描述

beanFactory.getBean(ppName, BeanDefinitionRegistryPostProcessor.class)拿到的bean其实是ConfigurationClassPostProcessor。

解析下来就是关键先生ConfigurationClassPostProcessor类和invokeBeanDefinitionRegistryPostProcessors方法。

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

		for (BeanDefinitionRegistryPostProcessor postProcessor : postProcessors) {
			StartupStep postProcessBeanDefRegistry = applicationStartup.start("spring.context.beandef-registry.post-process")
					.tag("postProcessor", postProcessor::toString);
			postProcessor.postProcessBeanDefinitionRegistry(registry);
			postProcessBeanDefRegistry.end();
		}
	}

根据代码来看,就是执行ConfigurationClassPostProcessor类的postProcessBeanDefinitionRegistry方法,带上了registry这个参数,也就是DefaultListableBeanFacotry。

这个invokeBeanDefinitionRegistryPostProcessors方法的意思就是调用这个BeanDefinitionRegistryPostProcessor的postProcessBeanDefinitionRegistry方法,而ConfigurationClassPostProcessor类的postProcessBeanDefinitionRegistry方法是去加载并注册我们自定义的一些被spring管理的类到spring中。在本节中不会深入的去研究这个类的具体执行逻辑,将在下一章节进行分析。

invokeBeanDefinitionRegistryPostProcessors方法执行完成之后会清理currentRegistryProcessors集合。然后就开始第二次调用了。

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, beanFactory.getApplicationStartup());
			currentRegistryProcessors.clear();

其实第二次调用的这块代码和第一次调用的大差不差,主要是beanFactory.isTypeMatch(ppName, Ordered.class)的不同,第一次是PriorityOrdered.class。同时第二次不会处理第一次执行过的BeanFacotryPostProcessor。也就是processedBeans.contains(ppName)逻辑。

在这里插入图片描述

第二次调用beanFactory.getBeanNamesForType(BeanDefinitionRegistryPostProcessor.class, true, false)除了第一次出现的org.springframework.context.annotation.internalConfigurationAnnotationProcessor还有两个我自定义的类。

@Component
public class CloudBeanDefinitionRegistryPostProcessor implements BeanDefinitionRegistryPostProcessor , PriorityOrdered {
	@Override
	public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {
		System.out.println("beanFactoryPostProcessor used by cloud");
	}

	@Override
	public void postProcessBeanDefinitionRegistry(BeanDefinitionRegistry registry) throws BeansException {
		System.out.println("BeanDefinitionRegistryPostProcessor used by cloud");
	}

	@Override
	public int getOrder() {
		return 100;
	}
}

因为第一次调用的时候执行了ConfigurationClassPostProcessor类的postProcessBeanDefinitionRegistry方法,会把我们交给spring管理的beanDefinition注册到beanFactory中,所以第二次调用这个方法的时候就会把自定义的加载起来,当然三方jar包也可能做同样的事情,比如mybatis plus。

invokeBeanDefinitionRegistryPostProcessors方法还是会执行这些自定的BeanDefinitionRegistryPostProcessor的postProcessBeanDefinitionRegistry方法。执行完成之后继续清理currentRegistryProcessors集合。

接下来开始调用第三次,为什么会出现第三次,就是因为 beanFactory.isTypeMatch(ppName, Ordered.class)和beanFactory.isTypeMatch(ppName, PriorityOrdered.class),相当于自定义的没有实现这两个接口的就在这里一次性处理完。

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

在if方法的最后有两行代码比较重要。

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

其实重要的就是这个方法,调用BeanFacotyPostProcessors的postProcessBeanFactory方法。也就是说自定义的这些BeanDefinitionRegistryPostProcessor会先执行BeanDefinitionRegistryPostProcessor的postProcessBeanDefinitionRegistry方法,待所有的BeanDefinitionRegistryPostProcessor执行完成之后再调用这些自定义的BeanDefinitionRegistryPostProcessor的postProcessBeanFactory方法。因为双方存在继承关系。

至此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!
	
		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<>();

**postProcessorNames:**获取的是当前beanFactory中的实现了BeanFactoryPostProcessor的bean的名称。

**priorityOrderedPostProcessors:**很明显哈实现了PriorityOrdered的BeanFactoryPostProcessor存放在这,存放的是bean哦。

**orderedPostProcessorNames:**存放的是实现了Ordered的BeanFactoryPostProcessor,存放的是名称。

**nonOrderedPostProcessorNames:**存放的是没有实现排序的BeanFactoryPostProcessor,存放的是名称。

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

接下来就是排序和invokeBeanFactoryPostProcessors,分别执行这几个集合中的BeanFactoryPostProcessor的postProcessBeanFactory方法。

总结

本章主要分析了AbstractApplicationContext.refresh方法中的invokeBeanFactoryPostProcessors(beanFactory)方法,其中ConfigurationClassPostProcessor类的postProcessBeanDefinitionRegistry方法和排序方法将在下一章进行分析和讲解,循序渐进的完成整个逻辑的讲解。

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/1025378.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

9月第3周榜单丨哔哩哔哩飞瓜数据B站UP主排行榜发布!

飞瓜轻数发布2023年9月11日-9月17日飞瓜数据UP主排行榜&#xff08;B站平台&#xff09;&#xff0c;通过充电数、涨粉数、成长指数、带货数据等维度来体现UP主账号成长的情况&#xff0c;为用户提供B站号综合价值的数据参考&#xff0c;根据UP主成长情况用户能够快速找到运营能…

每日一题~二叉搜索树中的插入操作

题目链接&#xff1a;701. 二叉搜索树中的插入操作 - 力扣&#xff08;LeetCode&#xff09; 题目描述&#xff1a; 思路分析&#xff1a;由题可知&#xff0c;题目的要求是给我们一个二叉搜索树和一个 val&#xff0c;将这个 val 插入到二叉搜索树中&#xff0c;并且这个树仍…

新型BI解决方案:SaaS BI,在浏览器上分析数据

在当今数字化时代&#xff0c;企业需要处理海量数据以制定精确的业务策略。然而&#xff0c;传统BI工具的繁琐安装和配置过程&#xff0c;让许多企业望而却步。幸运的是&#xff0c;一种新型的商业智能&#xff08;BI&#xff09;解决方案——SaaS BI系统&#xff0c;解决了这个…

戴口罩 目标检测数据集-12000张

今天要介绍的数据集则是戴口罩 目标检测数据集&#xff1a; 数据集名称&#xff1a;戴口罩 目标检测数据集 数据集格式&#xff1a;Pascal VOC格式(不包含分割路径的txt文件和yolo格式的txt文件&#xff0c;仅仅包含jpg图片和对应的xml) 图片数量(jpg文件个数)&#xff1a;以…

面试常谈的Binder理解,每个人都不一样~

面试官提了一个问题&#xff0c;我们来看看 &#x1f60e;、&#x1f628; 和 &#x1f914;️ 三位同学的表现如何吧 &#x1f60e; 自认为无所不知&#xff0c;水平已达应用开发天花板&#xff0c;目前月薪 10k 面试官️&#xff1a;谈谈你对 binder 的理解 &#x1f60e;&a…

Topaz Photo AI for Mac 图像智能ai降噪工具

Topaz Photo AI是一款基于人工智能技术的图像编辑软件&#xff0c;它可以帮助用户提升照片质量&#xff0c;使外观更加清晰锐利。这款软件不仅可作为独立的软件使用&#xff0c;也可作为Photoshop的插件&#xff0c;以及能在Lightroom Classic、Capture One中调用。 Topaz Pho…

【Android】关于Activity的onSaveInstanceState生命周期

最近笔者求职时面试一家大厂&#xff0c;被问到Activity的生命周期&#xff0c;其中面试官着重问了onSaveInstanceState的调用是在onStop之前还是之后&#xff0c;本人当时有点蒙圈&#xff0c;之前也没有关注它到底是在OnStop之前还是之后。 但是这个方法在什么时候调用的重要…

Centos7原生hadoop环境,搭建Impala集群和负载均衡配置

Centos7原生hadoop环境&#xff0c;搭建Impala集群和负载均衡配置 impala介绍 Impala集群包含一个Catalog Server (Catalogd)、一个Statestore Server (Statestored) 和若干个Impala Daemon (Impalad)。Catalogd主要负责元数据的获取和DDL的执行&#xff0c;Statestored主要负…

电商领域五强对比:Amazon、eBay、Wish、Target、Newegg,谁更胜一筹?(测评补单)

随着互联网的快速发展&#xff0c;电子商务成为了现代消费的主要方式。在众多电商平台中&#xff0c;Amazon、eBay、Wish、Target、Newegg是备受瞩目的电商巨头。它们在全球范围内拥有庞大的用户群体&#xff0c;提供了丰富的商品选择和便捷的购物体验。本文将对这些电商平台进…

Python网页信息爬取脚本

文章目录 获取整个页面所有源码筛选出源码中图片地址将图片下载到本地完整脚本 获取整个页面所有源码 该步骤可以用requests模块实现&#xff0c;分为下面步骤&#xff1a; 定义一个URL 地址; 发送HTTP 请求&#xff1b; 处理HTTP 响应。 下面代码定义了一个get_Html方法&…

jenkins中添加sonnarqube与OWASP Dependency-Check

jenkins jenkins离线插件地址&#xff1a; http://updates.jenkins-ci.org/download/plugins https://updates.jenkins.io/download/plugins https://mirrors.tuna.tsinghua.edu.cn/jenkins/plugins 国内linux 安装jdk11 文档&#xff1a; https://blog.51cto.co…

流量狂飙!暴涨2000万播放成B站创作标杆

“民以食为天”&#xff0c;美食品类内容是人们日常生活所需延伸出来的一个内容版块&#xff0c;用户浏览量大、众多内容创作者并驱争先&#xff0c;一直到今天&#xff0c;所有人有目共睹美食内容是如何在“内卷”。 饶是如此赛道拥挤的美食圈&#xff0c;也有众多创作者不断…

java字符串压缩和字符串解压

java字符串压缩和字符串解压 运行效果 java工具类 CompressUtil.java import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.serializer.SerializerFeature; import org.apache.commons.codec.binary.Base64;import java.io.BufferedReader; import java.io.Byte…

【LeetCode-中等题】116. 填充每个节点的下一个右侧节点指针

文章目录 题目方法一&#xff1a;直接让每层不是最后一个的节点指向此时队首元素方法二&#xff1a;用list记录下每层的节点 然后再做链接 题目 方法一&#xff1a;直接让每层不是最后一个的节点指向此时队首元素 class Solution {public Node connect(Node root) {if(root nu…

健身完全手册

文章目录 饮食完全手册摄入总量日内分配来源和配餐方法专题&错误 训练完全手册训练分化动作模式胸背手肩腿臀腹训练计划 减脂完全手册胸肌训练&#xff08;原理动作计划饮食&#xff09;健身训练的分化、动作、配重体态大师 饮食完全手册 参考视频&#xff1a;&#x1f4a…

什么是Web浏览器的缓存机制?如何控制和清除浏览器缓存?

聚沙成塔每天进步一点点 ⭐ 专栏简介⭐ Web浏览器的缓存机制⭐ 浏览器缓存的工作原理⭐ 控制和清除浏览器缓存控制缓存 ⭐ 清除缓存⭐ 写在最后 ⭐ 专栏简介 前端入门之旅&#xff1a;探索Web开发的奇妙世界 欢迎来到前端入门之旅&#xff01;感兴趣的可以订阅本专栏哦&#xf…

YashanDB混合存储揭秘:行式存储如何为高效TP业务保驾护航(上)

上一篇文章《深度干货 | 揭秘YashanDB融合存储引擎》 https://mp.weixin.qq.com/s/yipJcEAH3fVA-_hnUvOiKA从存储结构、事务引擎、高可用等方面介绍了YashanDB存储引擎的整体架构。本篇为大家详细解读YashanDB行式存储技术。 背景 数据库底层组织数据的方式主要分为行式存储和…

成集云 | 金蝶云星空集成聚水潭ERP(金蝶云星空主管库存)| 解决方案

源系统成集云目标系统 方案介绍 金蝶云星空是金蝶软件&#xff08;中国&#xff09;有限公司研发的新一代战略性企业管理软件&#xff0c;致力于为企业提供端到端的供应链整体解决方案&#xff0c;它可以帮助企业构建敏捷供应链体系&#xff0c;降低供应链成本&#xff0c;提…

The existence and uniqueness of weak solution

See https://zhuanlan.zhihu.com/p/67522044 https://math.stackexchange.com/questions/1213260/what-is-a-good-definition-of-a-weak-solution

「聊设计模式」之模板方法模式(Template Method)

&#x1f3c6;本文收录于《聊设计模式》专栏&#xff0c;专门攻坚指数级提升&#xff0c;助你一臂之力&#xff0c;带你早日登顶&#x1f680;&#xff0c;欢迎持续关注&&收藏&&订阅&#xff01; 前言 在软件开发中&#xff0c;设计模式是经典的解决方案&#…