Spring源码分析:BeanFactoryPostProcessor

BeanFactoryPostProcessor会在invokeBeanFactoryPostProcessors(beanFactory)方法中被调用。
invokeBeanFactoryPostProcessors(beanFactory)方法在AbstractApplicationContext.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);

				// Invoke factory processors registered as beans in the context.
				// 调用BeanFactoryPostProcessor
				//将我们自己的bean转换为beanDefinition
				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.
				//推断构造方法
				//通过反射new对象
				finishBeanFactoryInitialization(beanFactory);

				// Last step: publish corresponding event.
				finishRefresh();
			}
			/**
			* ...代码段
			*/
	}

本方法会执行所有的实现了BeanFactoryPostProcessor及其子接口BeanDefinitionRegistryPostProcess的类的postProcessBeanDefinitionRegistry方法和postProcessBeanFactory方法

BeanFactoryPostProcessor:Bean工厂的后置处理器,类图:
Bean工厂的后置处理器类继承图
Spring IoC 容器允许 BeanFactoryPostProcessor 在容器实例化任何 bean 之前读取 bean 的定义,并可以修改它。

分析

invokeBeanFactoryPostProcessors

	protected void invokeBeanFactoryPostProcessors(ConfigurableListableBeanFactory beanFactory) {
		//通过getBeanFactoryPostProcessors()方法得到所有已注册的BeanFactoryPostPorcessor
		//通常情况下这里"已注册的BeanFactoryPostPorcessor"仅包含用户自定义的且手动添加(非注解添加)到上下文的BeanFactoryPostPorcessor
		//调用所有的BeanFactoryPostPorcessor(包括所有已注册和未注册的)
		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()));
		}
	}

getBeanFactoryPostProcessors

	//用户没有手动添加BeanFactoryPostProcessor到上下文时,返回空list
	public List<BeanFactoryPostProcessor> getBeanFactoryPostProcessors() {
		return this.beanFactoryPostProcessors;
	}

在invokeBeanFactoryPostProcessors方法中,首先通过getBeanFactoryPostProcessors方法等得到所有已注册的BeanFactoryPostProcessor的list,然后将此list作为参数传入PostProcessorRegistrationDelegate.invokeBeanFactoryPostProcessors。
通常情况下这里"已注册的BeanFactoryPostPorcessor"仅包含用户自定义的且手动添加(非注解添加)到上下文的BeanFactoryPostPorcessor。
如果用户没有手动添加BeanFactoryPostProcessor到上下文时,getBeanFactoryPostProcessors发放返回空list。
用户自定义的且手动添加(非注解添加)到上下文的BeanFactoryPostPorcessor?
用户自动义且通过注解添加到上下文的BeanFactoryPostPorcessor

@Component
public class MyAnnoBeanFactoryPostPorcessor implements BeanFactoryPostProcessor {
	@Override
	public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {
		System.out.println("MyAnnoBeanFactoryPostProcessor-----");
	}
}
@Component
public class MyAnnoBeanDefinitionRegistryPostProcess implements BeanDefinitionRegistryPostProcessor {
	@Override
	public void postProcessBeanDefinitionRegistry(BeanDefinitionRegistry registry) throws BeansException {
		System.out.println("MyAnnoBeanDefinitionRegistryPostProcess---postProcessBeanDefinitionRegistry");
	}

	@Override
	public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {
		System.out.println("MyAnnoBeanDefinitionRegistryPostProcess---postProcessBeanFactory");
	}
}

用户自动义且手动添加到上下文的BeanFactoryPostPorcessor

public class MyBeanFactoryPostProcessor implements BeanFactoryPostProcessor {
	@Override
	public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {
		System.out.println("MyBeanFactoryPostPorcessor----");
	}
}
public class MyBeanDefinitionRegistryPostProcess implements BeanDefinitionRegistryPostProcessor {
	@Override
	public void postProcessBeanDefinitionRegistry(BeanDefinitionRegistry registry) throws BeansException {
		System.out.println("MyBeanDefinitionRegistryPostProcess---postProcessBeanDefinitionRegistry");
	}

	@Override
	public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {
		System.out.println("MyBeanDefinitionRegistryPostProcess---postProcessBeanFactory");
	}
}
	public static void main(String[] args) {
//		AnnotationConfigApplicationContext ac = new AnnotationConfigApplicationContext(AppConfig.class);
		MyBeanFactoryPostProcessor myBeanFactoryPostProcessor = new MyBeanFactoryPostProcessor();
		MyBeanDefinitionRegistryPostProcess myBeanDefinitionRegistryPostProcess = new MyBeanDefinitionRegistryPostProcess();
		AnnotationConfigApplicationContext ac = new AnnotationConfigApplicationContext();
		ac.addBeanFactoryPostProcessor(myBeanFactoryPostProcessor);
		ac.addBeanFactoryPostProcessor(myBeanDefinitionRegistryPostProcess);
		ac.register(AppConfig.class);
		ac.refresh();
		System.out.println(ac.getBean("indexService"));
	}

PostProcessorRegistrationDelegate.invokeBeanFactoryPostProcessors

	/**
	 * 调用所有的BeanFactoryPostProcessor及其子接口BeanDefinitionRegistryPostProcess的实现类
	 * 的postProcessBeanDefinitionRegistry方法和postProcessBeanFactory方法
	 *
	 * 调用顺序为:
	 * 1,手动添加到上下文的BeanDefinitionRegistryPostProcess接口的实现类的postProcessBeanDefinitionRegistry方法
	 * 2,实现PriorityOrdered接口且是通过注解添加到上下文的BeanDefinitionRegistryPostProcess接口的实现类的postProcessBeanDefinitionRegistry方法
	 * 		其中ConfigurationClassPostProcessor的postProcessBeanDefinitionRegistry方法
	 * 		完成用户bean的beanDefinition扫描并放入beanDefinitionMap和beanDefinitionNames中
	 * 3,实现Order接口且是通过注解添加到上下文的BeanDefinitionRegistryPostProcess接口的实现类的postProcessBeanDefinitionRegistry方法
	 * 4,通过注解添加到上下文的BeanDefinitionRegistryPostProcess接口的实现类的postProcessBeanDefinitionRegistry方法
	 * 	注意:执行postProcessBeanDefinitionRegistry可能会添加新的BeanDefinitionRegistryPostProcess,
	 * 		所以最后通过while循环执行,直到没有新的为止
	 * 5,手动添加到上下文的BeanDefinitionRegistryPostProcess接口的实现类的postProcessBeanFactory方法
	 * 6,通过注解添加到上下文的BeanDefinitionRegistryPostProcess接口的实现类的postProcessBeanFactory方法
	 * 		包括ConfigurationClassPostProcessor的postProcessBeanFactory方法
	 * 7,手动添加到上下文的BeanFactoryPostPorcessor的实现类的postProcessBeanFactory方法
	 * 8,实现PriorityOrdered接口且是通过注解添加到上下文的BeanFactoryPostPorcessor接口的实现类的postProcessBeanFactory方法
	 * 9,实现Ordered接口且是通过注解添加到上下文的BeanFactoryPostPorcessor接口的实现类的postProcessBeanFactory方法
	 * 10,通过注解添加到上下文的BeanFactoryPostPorcessor接口的实现类postProcessBeanFactory方法
	 */
	public static void invokeBeanFactoryPostProcessors(
			ConfigurableListableBeanFactory beanFactory, List<BeanFactoryPostProcessor> beanFactoryPostProcessors) {

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

		//beanFactory = new DefaultListableBeanFactory()
		//DefaultListableBeanFactory实现了BeanDefinitionRegistry,因此判断为true
		if (beanFactory instanceof BeanDefinitionRegistry) {
			BeanDefinitionRegistry registry = (BeanDefinitionRegistry) beanFactory;
			//注意这两个list的泛型
			//这两个list的作用是:在调用所有的postProcessBeanDefinitionRegistry方法后,用于调用postProcessBeanFactory方法
			List<BeanFactoryPostProcessor> regularPostProcessors = new ArrayList<>();
			List<BeanDefinitionRegistryPostProcessor> registryProcessors = new ArrayList<>();

			//首先处理入参中的beanFactoryPostProcessors
			for (BeanFactoryPostProcessor postProcessor : beanFactoryPostProcessors) {
				if (postProcessor instanceof BeanDefinitionRegistryPostProcessor) {
					//如果是BeanDefinitionRegistryPostProcessor,
					//直接调用postProcessBeanDefinitionRegistry方法
					//并放入相应的list
					BeanDefinitionRegistryPostProcessor registryProcessor =
							(BeanDefinitionRegistryPostProcessor) postProcessor;
					registryProcessor.postProcessBeanDefinitionRegistry(registry);
					registryProcessors.add(registryProcessor);
				}
				else {
					//否则就是BeanFactoryPostProcessor,放入对应的list
					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<>();

			// First, invoke the BeanDefinitionRegistryPostProcessors that implement PriorityOrdered.
			//首先,调用所有实现PriorityOrdered接口且已添加到上下文的BeanDefinitionRegistryPostProcessors的实现类的postProcessBeanDefinitionRegistry方法
			/**
			 * 在用户没有自定义BeanDefinitionRegistryPostProcessor的情况下,此处只有一个ConfigurationClassPostProcessor
			 */
			//1,找出所有BeanDefinitionRegistryPostProcessor的实现类
			//	这个方法会多次调用,因为BeanDefinitionRegistryPostProcessor执行后可能会添加新的BeanDefinitionRegistryPostProcessors
			//2,过滤实现PriorityOrdered接口
			//3,过滤已经调用过的
			//4,排序
			//5,加入list
			//6,依次调用postProcessBeanDefinitionRegistry
			//7,清空临时变量
			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);
				}
			}
			sortPostProcessors(currentRegistryProcessors, beanFactory);
			registryProcessors.addAll(currentRegistryProcessors);
			//执行ConfigurationClassPostProcessor的postProcessBeanDefinitionRegistry方法,扫描用户bean,放入beanDefinitionMap和beanDefinitionNames
			invokeBeanDefinitionRegistryPostProcessors(currentRegistryProcessors, registry);
			currentRegistryProcessors.clear();

			// Next, invoke the BeanDefinitionRegistryPostProcessors that implement Ordered.
			//接下来,调用所有实现Ordered接口且已添加到上下文的BeanDefinitionRegistryPostProcessor的实现类的postProcessBeanDefinitionRegistry方法
			//除第二步过滤Order接口外,步骤与上面一致
			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);
			currentRegistryProcessors.clear();

			// Finally, invoke all other BeanDefinitionRegistryPostProcessors until no further ones appear.
			//最后,调用所有剩下的已添加到上下文的BeanDefinitionRegistryPostProcessor的实现类的postProcessBeanDefinitionRegistry方法
			//上面已经说过,调用postProcessBeanDefinitionRegistry方法时,可能会添加新的BeanDefinitionRegistryPostProcessor,
			// 所以此处使用循环,直到没有新的BeanDefinitionRegistryPostProcessor为止
			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);
				currentRegistryProcessors.clear();
			}

			// Now, invoke the postProcessBeanFactory callback of all processors handled so far.
			//调用所有BeanDefinitionRegistryPostProcessor实现类的postProcessBeanFactory方法
			invokeBeanFactoryPostProcessors(registryProcessors, beanFactory);
			//调用用户自定义的BeanFactoryPostProcessor接口的实现类且是手动添加到上下文(没有使用注解自动扫描)的postProcessBeanFactory方法
			invokeBeanFactoryPostProcessors(regularPostProcessors, beanFactory);
		}

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

		//开始调用用户使用注解添加的BeanFactoryPostProcessor接口的实现类的postProcessBeanFactory方法
		//执行顺序:1,实现PriorityOrdered接口;2,实现Ordered接口;3,其他
		// 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(priorityOrderedPostProcessors, beanFactory);
		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(orderedPostProcessors, beanFactory);
		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();
	}

执行过程可以看上面代码段的注释。
“执行postProcessBeanDefinitionRegistry可能会添加新的BeanDefinitionRegistryPostProcess”,这句话改怎么理解?
举例说明:

public class MyRegisterBeanDefinitionRegistryPostPorcessor implements BeanDefinitionRegistryPostProcessor {
	@Override
	public void postProcessBeanDefinitionRegistry(BeanDefinitionRegistry registry) throws BeansException {
		System.out.println("MyRegisterBeanDefinitionRegistryPostPorcessor---postProcessBeanDefinitionRegistry");
	}

	@Override
	public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {
		System.out.println("MyRegisterBeanDefinitionRegistryPostPorcessor---postProcessBeanFactory");
	}
}
@Component
public class MyAnnoBeanDefinitionRegistryPostProcess implements BeanDefinitionRegistryPostProcessor {
	@Override
	public void postProcessBeanDefinitionRegistry(BeanDefinitionRegistry registry) throws BeansException {
		BeanDefinition bd = registry.getBeanDefinition("myAnnoBeanDefinitionRegistryPostProcess");
		bd.setBeanClassName(MyRegisterBeanDefinitionRegistryPostPorcessor.class.getName());
		//将BeanDefinition的属性改变后,当做新的BeanDefinition注册到容器中
		registry.registerBeanDefinition("myRegisterBeanDefinitionRegistryPostPorcessor", bd);
		System.out.println("MyAnnoBeanDefinitionRegistryPostProcess---postProcessBeanDefinitionRegistry");
	}

	@Override
	public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {
		System.out.println("MyAnnoBeanDefinitionRegistryPostProcess---postProcessBeanFactory");
	}
}

MyRegisterBeanDefinitionRegistryPostPorcessor既没有通过注解,也没有手动添加到上下文中。
在调用MyAnnoBeanDefinitionRegistryPostProcess的postProcessBeanDefinitionRegistry方法时,将MyRegisterBeanDefinitionRegistryPostPorcessor包装成BeanDefinition注册到容器中,MyRegisterBeanDefinitionRegistryPostPorcessor中的方法也会在invokeBeanFactoryPostProcessors方法的循环调用阶段被调用。

总结

BeanFactoryPostProcessor作用于BeanDefinition阶段(bean实例化之前),可以修改bean的定义。
BeanDefinitionRegistryPostPorcessor比BeanFactoryPostProcessors有更高的优先级,在BeanFactoryPostProcessors之前执行。
BeanDefinitionRegistryPostPorcessor执行过程中会出现“套娃现象”:注册新的BeanFactoryPostProcessors。
调用顺序:
1,手动添加到上下文的BeanDefinitionRegistryPostProcess接口的实现类的postProcessBeanDefinitionRegistry方法
2,实现PriorityOrdered接口且是通过注解添加到上下文的BeanDefinitionRegistryPostProcess接口的实现类的postProcessBeanDefinitionRegistry方法
* 其中ConfigurationClassPostProcessor的postProcessBeanDefinitionRegistry方法
* 完成用户bean的beanDefinition扫描并放入beanDefinitionMap和beanDefinitionNames中
3,实现Order接口且是通过注解添加到上下文的BeanDefinitionRegistryPostProcess接口的实现类的postProcessBeanDefinitionRegistry方法
4,通过注解添加到上下文的BeanDefinitionRegistryPostProcess接口的实现类的postProcessBeanDefinitionRegistry方法
* 注意:执行postProcessBeanDefinitionRegistry可能会添加新的BeanDefinitionRegistryPostProcess,
* 所以最后通过while循环执行,直到没有新的为止
5,手动添加到上下文的BeanDefinitionRegistryPostProcess接口的实现类的postProcessBeanFactory方法
6,通过注解添加到上下文的BeanDefinitionRegistryPostProcess接口的实现类的postProcessBeanFactory方法
* 包括ConfigurationClassPostProcessor的postProcessBeanFactory方法
7,手动添加到上下文的BeanFactoryPostPorcessor的实现类的postProcessBeanFactory方法
8,实现PriorityOrdered接口且是通过注解添加到上下文的BeanFactoryPostPorcessor接口的实现类的postProcessBeanFactory方法
9,实现Ordered接口且是通过注解添加到上下文的BeanFactoryPostPorcessor接口的实现类的postProcessBeanFactory方法
10,通过注解添加到上下文的BeanFactoryPostPorcessor接口的实现类postProcessBeanFactory方法

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值