基于springboot2.1.4
1、BeanFactoryPostProcessor
主要用于对beanDefinition的修改,对beanFactory中的相关参数进行修改
eg:org.springframework.context.annotation.ConfigurationClassPostProcessor#postProcessBeanFactory


在执行invokeBeanFactoryPostProcessors的时候,首先从context中获取到前面手动new然后put入的BeanFactoryPostProcessors

在invokeBeanFactoryPostProcessors方法中,首先是对BeanDefinitionRegistryPostProcessor类型的processor进行处理

当通过beandefinition查找时,beanDefinition可能通过代码手动添加,或者通过扫描注解添加,此时都会提前实例化。这些通过beandefinition实例化的bean不会加入到context的beanFactoryPostProcessors列表中。

自定义demo如下:

2、BeanPostProcessor
主要用于bean实例化的前置后置处理eg:org.springframework.beans.factory.annotation.InitDestroyAnnotationBeanPostProcessor

前置后置方法执行时机
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory#doCreateBean-->org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory#initializeBean(java.lang.String, java.lang.Object, org.springframework.beans.factory.support.RootBeanDefinition)

不过需要注意的是有些BeanPostProcessor是实现了MergedBeanDefinitionPostProcessor或者InstantiationAwareBeanPostProcessor(这两个接口也是继承了BeanPostProcessor接口),在执行前置后置方法时,如果不清楚一些变量从何而来,可以尝试从这两个接口特有的实现方法中找。自定义demo如下:

3、SmartInitializingSingleton
在所有的单例实例化完之后,对满足条件的实例做后续处理eg:org.springframework.context.event.EventListenerMethodProcessor

自定义demo
/**
* 参考org.springframework.context.event.EventListenerMethodProcessor
*/
@Component
public class AnnoCustomBeanSingletonProcessor implements SmartInitializingSingleton {
@Override
public void afterSingletonsInstantiated() {
System.out.println("AnnoCustomBeanSingletonProcessor afterSingletonsInstantiated");
}
}
4、MergedBeanDefinitionPostProcessor
5、InstantiationAwareBeanPostProcessor
除了BeanPostProcessor的两个接口方法外还有如下两个接口,在实例化后初始化前,完成成员变量的填充
postProcessProperties(PropertyValues pvs, Object bean, String beanName)
postProcessPropertyValues(
PropertyValues pvs, PropertyDescriptor[] pds, Object bean, String beanName)
6、Aware接口
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory#invokeAwareMethods
在bean填充完成员变量之后,在bean初始化时先完成几个Aware接口的回调((BeanNameAware) bean).setBeanName(beanName);、((BeanClassLoaderAware) bean).setBeanClassLoader(bcl);、((BeanFactoryAware) bean).setBeanFactory(AbstractAutowireCapableBeanFactory.this);
7、org.springframework.beans.factory.config.SmartInstantiationAwareBeanPostProcessor
继承自InstantiationAwareBeanPostProcessor
可用于自定义检测构造方法等Constructor<?>[] determineCandidateConstructors(Class<?> beanClass, String beanName)
网友评论