Spring源码导读之BeanPostProcessor

Spring源码导读

目录

如何感知

注册PostProcessorRegistrationDelegate

BeanPostProcessorChecker

ApplicationListenerDetector

案例

autowiredAnnotationBeanPostProcessor:

自定义BeanPostProcessor实现对象的代理


如何感知

singleton中已经列出bean创建中调用BeanPostProcessor的链路

比如看下这条链路的

determineConstructorsFromBeanPostProcessors 方法

AbstractAutowireCapableBeanFactory#createBean(RootBeanDefinition, .Object[])
        ==》AbstractAutowireCapableBeanFactory#doCreateBean

                ==》AbstractAutowireCapableBeanFactory#createBeanInstance

                             ==》AbstractAutowireCapableBeanFactory#determineConstructorsFromBeanPostProcessors(@Nullable Class<?> beanClass, String beanName)

                                     ==》SmartInstantiationAwareBeanPostProcessor#determineCandidateConstructors(Class<?> beanClass, String beanName)

 

protected Constructor<?>[] determineConstructorsFromBeanPostProcessors(@Nullable Class<?> beanClass, String beanName)
		throws BeansException {
	// 判断是否由实例化感知的BeanPostProcessors
	if (beanClass != null && hasInstantiationAwareBeanPostProcessors()) {
		for (BeanPostProcessor bp : getBeanPostProcessors()) {
			if (bp instanceof SmartInstantiationAwareBeanPostProcessor) {
				SmartInstantiationAwareBeanPostProcessor ibp = (SmartInstantiationAwareBeanPostProcessor) bp;
				Constructor<?>[] ctors = ibp.determineCandidateConstructors(beanClass, beanName);
				if (ctors != null) {
					return ctors;
				}
			}
		}
	}
	return null;
}
	protected boolean hasInstantiationAwareBeanPostProcessors() {
		return this.hasInstantiationAwareBeanPostProcessors;
	}

如果 hasInstantiationAwareBeanPostProcessors == true,那么Spring容器就会调用。那么hasInstantiationAwareBeanPostProcessors 是什么时候设置为true的呢?

在 org.springframework.context.support.AbstractApplicationContext#refresh 方法中 有一行代码 registerBeanPostProcessors,它对BeanPostProcessors进行了注册。

BeanFactoryPostProcessor一样, 它的注册也是用到了PostProcessorRegistrationDelegate这个类。不一样的是,BeanFactoryPostProcessor会在这个类中被 创建和调用,而且中间还会可能产生新的BeanFactoryPostProcessor定义,同样也会被创建和调用,而BeanPostProcessor在这个类中是被创建和注册后面才会被调用。

protected void registerBeanPostProcessors(ConfigurableListableBeanFactory beanFactory) {
	PostProcessorRegistrationDelegate.registerBeanPostProcessors(beanFactory, this);
}

注册PostProcessorRegistrationDelegate

PostProcessorRegistrationDelegate#registerBeanPostProcessors(ConfigurableListableBeanFactory, AbstractApplicationContext)

创建并注册BeanPostProcessors:

public static void registerBeanPostProcessors(
		ConfigurableListableBeanFactory beanFactory, AbstractApplicationContext applicationContext) {

	// 按照类型从bean定义中寻找所有BeanPostProcessor的beanName
	String[] postProcessorNames = beanFactory.getBeanNamesForType(BeanPostProcessor.class, true, false);

	// 将beanFactory中原本就自带的BeanPostProcessor 数量 + beanDefinition中的 BeanPostProcessor + 1 作为 beanProcessor的总量
	int beanProcessorTargetCount = beanFactory.getBeanPostProcessorCount() + 1 + postProcessorNames.length;
	// +1 是因为这里又加入了一个。
	beanFactory.addBeanPostProcessor(new BeanPostProcessorChecker(beanFactory, beanProcessorTargetCount));

	// priorityOrderedPostProcessors 优先级最高的PostProcessors
	// internalPostProcessors 内部的 PostProcessors
	// orderedPostProcessorNames 优先级稍次的 PostProcessors
	// nonOrderedPostProcessorNames 常规 的 PostProcessors
	// 为什么 优先级稍次的 PostProcessors 和 常规 的 PostProcessors只是先记录名字而不先创建 ?
	// 因为优先级最高的PostProcessors在 调用时时运行修改他们的 因此先记录再创建。
	List<BeanPostProcessor> priorityOrderedPostProcessors = new ArrayList<>();
	List<BeanPostProcessor> internalPostProcessors = new ArrayList<>();
	List<String> orderedPostProcessorNames = new ArrayList<>();
	List<String> nonOrderedPostProcessorNames = new ArrayList<>();
	for (String ppName : postProcessorNames) {
		// 如果实现了PriorityOrdered 那么则加入最高优先级 直接创建他们并加入到priorityOrderedPostProcessors
		if (beanFactory.isTypeMatch(ppName, PriorityOrdered.class)) {
			BeanPostProcessor pp = beanFactory.getBean(ppName, BeanPostProcessor.class);
			priorityOrderedPostProcessors.add(pp);
			// 如果它还实现了MergedBeanDefinitionPostProcessor 则加入内部的 PostProcessors中
			if (pp instanceof MergedBeanDefinitionPostProcessor) {
				internalPostProcessors.add(pp);
			}
		}
		// 如果仅仅只是实现Ordered, 则 记录名字
		else if (beanFactory.isTypeMatch(ppName, Ordered.class)) {
			orderedPostProcessorNames.add(ppName);
		}
		// 常规的PostProcessor,记录名字
		else {
			nonOrderedPostProcessorNames.add(ppName);
		}
	}

	// 首先注册具有最高优先级的
	sortPostProcessors(priorityOrderedPostProcessors, beanFactory);
	registerBeanPostProcessors(beanFactory, priorityOrderedPostProcessors);

	//  接着创建和注册Ordered优先级的
	List<BeanPostProcessor> orderedPostProcessors = new ArrayList<>();
	for (String ppName : orderedPostProcessorNames) {
		BeanPostProcessor pp = beanFactory.getBean(ppName, BeanPostProcessor.class);
		orderedPostProcessors.add(pp);
		if (pp instanceof MergedBeanDefinitionPostProcessor) {
			// 如果它还实现了MergedBeanDefinitionPostProcessor 则加入内部的 PostProcessors中
			internalPostProcessors.add(pp);
		}
	}
	sortPostProcessors(orderedPostProcessors, beanFactory);
	registerBeanPostProcessors(beanFactory, orderedPostProcessors);

	// 创建和注册常规的
	List<BeanPostProcessor> nonOrderedPostProcessors = new ArrayList<>();
	for (String ppName : nonOrderedPostProcessorNames) {
		BeanPostProcessor pp = beanFactory.getBean(ppName, BeanPostProcessor.class);
		nonOrderedPostProcessors.add(pp);
		if (pp instanceof MergedBeanDefinitionPostProcessor) {
			// 如果它还实现了MergedBeanDefinitionPostProcessor 则加入内部的 PostProcessors中
			internalPostProcessors.add(pp);
		}
	}
	registerBeanPostProcessors(beanFactory, nonOrderedPostProcessors);

	// 最后再次注册内部的 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).
	beanFactory.addBeanPostProcessor(new ApplicationListenerDetector(applicationContext));
}

 

registerBeanPostProcessors

private static void registerBeanPostProcessors(
		ConfigurableListableBeanFactory beanFactory, List<BeanPostProcessor> postProcessors) {

	for (BeanPostProcessor postProcessor : postProcessors) {
		beanFactory.addBeanPostProcessor(postProcessor);
	}
}

AbstractBeanFactory#addBeanPostProcessor
 

public void addBeanPostProcessor(BeanPostProcessor beanPostProcessor) {
	Assert.notNull(beanPostProcessor, "BeanPostProcessor must not be null");
	this.beanPostProcessors.remove(beanPostProcessor);
	// 注册
	this.beanPostProcessors.add(beanPostProcessor);
	if (beanPostProcessor instanceof InstantiationAwareBeanPostProcessor) {
		// 打上感知标记
		this.hasInstantiationAwareBeanPostProcessors = true;
	}
	if (beanPostProcessor instanceof DestructionAwareBeanPostProcessor) {
		this.hasDestructionAwareBeanPostProcessors = true;
	}
}

BeanPostProcessorChecker

再回头看这两行代码,这两行代码加入了一个checker


public static void registerBeanPostProcessors(
		ConfigurableListableBeanFactory beanFactory, AbstractApplicationContext applicationContext) {

	// ...............
	
	// 将beanFactory中原本就自带的BeanPostProcessor 数量 + beanDefinition中的 BeanPostProcessor + 1 作为 beanProcessor的总量
	int beanProcessorTargetCount = beanFactory.getBeanPostProcessorCount() + 1 + postProcessorNames.length;
	// +1 是因为这里又加入了一个。
	beanFactory.addBeanPostProcessor(new BeanPostProcessorChecker(beanFactory, beanProcessorTargetCount));
	
	// ...............

}

BeanPostProcessorChecker 实现了BeanPostProcessor,它是第一个被创建的BeanPostProcessor。那么后面所有的bean创建时都会进入它的拦截。它主要拦截的 那些 被 后面BeanPostProcessor 的所依赖的其他类型bean。被BeanPostProcessor依赖的bean,是不会被所有BeanPostProcessor拦截的,那么就针对它打一行日志。意思就是:

"当前这个bean ,没有资格被所有BeanPostProcessor都处理一次(例如:它不能被动态代理)"

PostProcessorRegistrationDelegate.BeanPostProcessorChecker#postProcessAfterInitialization的源码:

public Object postProcessAfterInitialization(Object bean, String beanName) {
	// 不拦截 BeanPostProcessor, 不拦截 Spring基础架构的bean。意思就是拦截普通的用户bean
	// 如果 getBeanPostProcessorCount < this.beanPostProcessorTargetCount 说明,当前还处于BeanPostProcessors的创建阶段
	// 如果这个阶段有其他类型的bean被依赖而创建(比如singleton) 就会再次打一行日志
	// "这个bean没有资格被所有BeanPostProcessor处理"
	if (!(bean instanceof BeanPostProcessor) && !isInfrastructureBean(beanName) &&
			this.beanFactory.getBeanPostProcessorCount() < this.beanPostProcessorTargetCount) {
		if (logger.isInfoEnabled()) {
		    // 
			logger.info("Bean '" + beanName + "' of type [" + bean.getClass().getName() +
					"] is not eligible for getting processed by all BeanPostProcessors " +
					"(for example: not eligible for auto-proxying)");
		}
	}
	return bean;
}

bean的创建顺序:

  1. beanFactoryPostProcessor    --> 修改或增加bean定义,如果beanFactoryPostProcessor本身需要注入其他的bean,那么这个bean的创建就会被提前。
  2. beanPostProcessor                --> 拦截整个Bean的创建过程,如果beanPostProcessor本身需要注入其他的bean,那么这个bean的创建就会被提前。
  3. singletonBean | factoryBean (除了被PostProcessor 依赖的bean,他们会被提前)
  4. factoryBean 实现了SmartFactoryBean 并且isEargerInit return true 的getObject返回的bean
  5. PrototypeBean

 

ApplicationListenerDetector

看最后一行代码:

public static void registerBeanPostProcessors(
		ConfigurableListableBeanFactory beanFactory, AbstractApplicationContext applicationContext) {
		
    // ..............
		
	// Re-register post-processor for detecting inner beans as ApplicationListeners,
	// moving it to the end of the processor chain (for picking up proxies etc).
	beanFactory.addBeanPostProcessor(new ApplicationListenerDetector(applicationContext));
}

在容器中注册了一个ApplicationListenerDetector,它的作用是对实现了ApplicationListener的bean进行注册。

class ApplicationListenerDetector implements DestructionAwareBeanPostProcessor, MergedBeanDefinitionPostProcessor 

 

它实现了MergedBeanDefinitionPostProcessor.postProcessMergedBeanDefinition 的方法。这个方法在bean创建之后,初始化之前被调用,这个方法是唯一一次可以拿到bean定义的方法。

AbstractAutowireCapableBeanFactory#createBean(RootBeanDefinition, .Object[])
    ==》AbstractAutowireCapableBeanFactory#doCreateBean
        ==》AbstractAutowireCapableBeanFactory#applyMergedBeanDefinitionPostProcessors
            ==》MergedBeanDefinitionPostProcessor#postProcessMergedBeanDefinition(RootBeanDefinition beanDefinition, Class<?> beanType, String beanName)

public void postProcessMergedBeanDefinition(RootBeanDefinition beanDefinition, Class<?> beanType, String beanName) {
	// 获取beanDefinition, 是为了记录它的scope是不是gingleton
	this.singletonNames.put(beanName, beanDefinition.isSingleton());
}

ApplicationListenerDetector#postProcessAfterInitialization

public Object postProcessAfterInitialization(Object bean, String beanName) {
	// 对ApplicationListener的bean进行注册
	if (bean instanceof ApplicationListener) {
		// potentially not detected as a listener by getBeanNamesForType retrieval
		Boolean flag = this.singletonNames.get(beanName);
		// 仅支持single的bean
		if (Boolean.TRUE.equals(flag)) {
			// singleton bean (top-level or inner): register on the fly
			this.applicationContext.addApplicationListener((ApplicationListener<?>) bean);
		}
		// 如果不是单例, 则不支持, 打一行warn日志
		else if (Boolean.FALSE.equals(flag)) {
			if (logger.isWarnEnabled() && !this.applicationContext.containsBean(beanName)) {
				// inner bean with other scope - can't reliably process events
				logger.warn("Inner bean '" + beanName + "' implements ApplicationListener interface " +
						"but is not reachable for event multicasting by its containing ApplicationContext " +
						"because it does not have singleton scope. Only top-level listener beans are allowed " +
						"to be of non-singleton scope.");
			}
			this.singletonNames.remove(beanName);
		}
	}
	return bean;
}

案例

autowiredAnnotationBeanPostProcessor:

https://blog.csdn.net/lightj1996/article/details/107515420

自定义BeanPostProcessor实现对象的代理

https://blog.csdn.net/lightj1996/article/details/107442442

 

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值