前言
上一节核心方法中的invokeBeanFactoryPostProcessors(beanFactory) 主要逻辑是完成BeanDefinitionRegistryPostProcessor 接口和 BeanFactoryPostProcessor接口类型 对象 的 实例化以及 调用实现的方法。可以拿到beanFactory 和 beanDefinitionRegistry 对象在 其他Bean实例化之前 操作bean 以及 操作 Bean的BeanDefinition。
紧跟这个方法下面的是,registerBeanPostProcessors(beanFactory) :用来注册实现了BeanPostProcessor接口的类,实例化之后加入到BeanFactory中。
BeanPostProcessor接口
public interface BeanPostProcessor {
/**
* Apply this {@code BeanPostProcessor} to the given new bean instance <i>before</i> any bean
* initialization callbacks (like InitializingBean's {@code afterPropertiesSet}
* or a custom init-method). The bean will already be populated with property values.
* The returned bean instance may be a wrapper around the original.
* <p>The default implementation returns the given {@code bean} as-is.
* @param bean the new bean instance
* @param beanName the name of the bean
* @return the bean instance to use, either the original or a wrapped one;
* if {@code null}, no subsequent BeanPostProcessors will be invoked
* @throws org.springframework.beans.BeansException in case of errors
* @see org.springframework.beans.factory.InitializingBean#afterPropertiesSet
*/
@Nullable
default Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
return bean;
}
/**
* Apply this {@code BeanPostProcessor} to the given new bean instance <i>after</i> any bean
* initialization callbacks (like InitializingBean's {@code afterPropertiesSet}
* or a custom init-method). The bean will already be populated with property values.
* The returned bean instance may be a wrapper around the original.
* <p>In case of a FactoryBean, this callback will be invoked for both the FactoryBean
* instance and the objects created by the FactoryBean (as of Spring 2.0). The
* post-processor can decide whether to apply to either the FactoryBean or created
* objects or both through corresponding {@code bean instanceof FactoryBean} checks.
* <p>This callback will also be invoked after a short-circuiting triggered by a
* {@link InstantiationAwareBeanPostProcessor#postProcessBeforeInstantiation} method,
* in contrast to all other {@code BeanPostProcessor} callbacks.
* <p>The default implementation returns the given {@code bean} as-is.
* @param bean the new bean instance
* @param beanName the name of the bean
* @return the bean instance to use, either the original or a wrapped one;
* if {@code null}, no subsequent BeanPostProcessors will be invoked
* @throws org.springframework.beans.BeansException in case of errors
* @see org.springframework.beans.factory.InitializingBean#afterPropertiesSet
* @see org.springframework.beans.factory.FactoryBean
*/
@Nullable
default Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
return bean;
}
}
BeanPostProcessor接口可以说是Spring最重要的接口, 提供了两个方法,
- postProcessBeforeInitialization(bean,beanName) : 在bean初始化之前调用。
- postProcessAfterInitialization( bean,beanName) : 在bean初始化之后调用。
在bean的创建过程中, spring会通过该接口的实例集合,在特定的阶段 遍历实例 ,调用 实例的两个方法, 拿到入参里的bean和beanName ,对每一个bean进行反复的 修饰 后 再返回。
通过提前注册BeanPostProcessor实例,然后再用的时候,取出 对应类型的 实例集合, 遍历调用 方法, 可以 在遵守开闭原则的情况下 进行 功能的拓展 :只需要往容器中 注册BeanPostProcessor 类型的Bean, 实现方法 即可。 对调用的代码 没有任何侵入性。
常见的BeanPostProcessor接口 作用 :
InstantiationAwareBeanPostProcessor
postProcessAfterInstantiation(bw.getWrappedInstance(), beanName):
在bean实例化之后,属性注入之前对Bean,进行修改
SmartInstantiationAwareBeanPostProcessor
AutowiredAnnotationBeanPostProcessor
determineCandidateConstructors() :1. bean实例化时,获取合适的构造方法
2. 解析loopUp注解,添加到bd的MethodOverrides
InstantiationAwareBeanPostProcessorAdapter
ImportAwareBeanPostProcessor
postProcessProperties(pvs,bean,beanName) : Bean实现EnhancedConfiguration这个接口,调用它的setBeanFactory,对我们没用,业务代码无法实现ConfigurationClassEnhancer.EnhancedConfiguration,因为其非公共的class
MergedBeanDefinitionPostProcessor
AutowiredAnnotationBeanPostProcessor
postProcessMergedBeanDefinition(): 收集@Autowired,@Value的属性和方法
postProcessProperties() : 注入@Autowired/@Value的属性,方法
InitDestroyAnnotationBeanPostProcessor
postProcessMergedBeanDefinition() : 收集@PostConstruct,@PreDestroy
postProcessProperties() : 注入@Resource的属性
postProcessBeforeInitialization() : @ProConstrcut 方法的调用
CommonAnnotationBeanPostProcessor:
postProcessMergedBeanDefinition():收集@Resource,并调用父类InitDestroyAnnotationBeanPostProcessor
的postProcessMergedBeanDefinition()来收集@PostConstruct,@PreDestroy
ApplicationListenerDetector
applyBeanPostProcessorsAfterInitialization() : 判断是否是ApplicationListener类型,有加入到事件管理器中
ApplicationContextAwareProcessor
postProcessBeforeInitialization : EnvironmentAware、EmbeddedValueResolverAware、ResourceLoaderAware、
ApplicationEventPublisherAware、MessageSourceAware、ApplicationContextAware 接口的调用
ConfigurationClassPostProcessor.ImportAwareBeanPostProcessor
postProcessBeforeInitialization() :如果该类被B类@import进来,那么该方法会传入B类的注解元数据AnnotationMetadata
SmartInstantiationAwareBeanPostProcessor
AbstractAutoProxyCreator
applyBeanPostProcessorsAfterInitialization() : 符合条件生成代理,aop
注册BeanPostProcessor源码解析:
点进核心方法的registerBeanPostProcessors(beanFactory)方法
public static void registerBeanPostProcessors(
ConfigurableListableBeanFactory beanFactory, AbstractApplicationContext applicationContext) {
// 取出容器里 BeanPostProcessor类型 的bean的Name数组
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.
int beanProcessorTargetCount = beanFactory.getBeanPostProcessorCount() + 1 + postProcessorNames.length;
beanFactory.addBeanPostProcessor(new BeanPostProcessorChecker(beanFactory, beanProcessorTargetCount));
// Separate between BeanPostProcessors that implement PriorityOrdered,
// Ordered, and the rest.
// 用来装 实现了PriorityOrdered 接口的BeanPostProcessor 实例
List<BeanPostProcessor> priorityOrderedPostProcessors = new ArrayList<>();
// 用来装 内部的BeanPostProcessor实例
List<BeanPostProcessor> internalPostProcessors = new ArrayList<>();
// 用来装 实现了Ordered 接口的 BeanPostProcessor实例
List<String> orderedPostProcessorNames = new ArrayList<>();
// 用来装 其他的 BeanPostProcessor实例
List<String> nonOrderedPostProcessorNames = new ArrayList<>();
// 先是实例化 实现了 PriorityOrdered接口的
for (String ppName : postProcessorNames) {
if (beanFactory.isTypeMatch(ppName, PriorityOrdered.class)) {
// 先实例化实现了 PriorityOrdered接口的
BeanPostProcessor pp = beanFactory.getBean(ppName, BeanPostProcessor.class);
// 加到容器中
priorityOrderedPostProcessors.add(pp);
// 判断是否是内部的
if (pp instanceof MergedBeanDefinitionPostProcessor) {
internalPostProcessors.add(pp);
}
}
// 实现了 Ordered接口的 ,加对应容器里
else if (beanFactory.isTypeMatch(ppName, Ordered.class)) {
orderedPostProcessorNames.add(ppName);
}
else {
// 其他的,加对应容器里
nonOrderedPostProcessorNames.add(ppName);
}
}
// First, register the BeanPostProcessors that implement PriorityOrdered.
// 按PriorityOrdered 排序
sortPostProcessors(priorityOrderedPostProcessors, beanFactory);
// 加到beanFactory中的 beanPostProcessors 容器
registerBeanPostProcessors(beanFactory, priorityOrderedPostProcessors);
// Next, register the BeanPostProcessors that implement Ordered.
// 再注册 implement 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);
}
}
// 按Ordered排序
sortPostProcessors(orderedPostProcessors, beanFactory);
// 加到beanFactory中的 beanPostProcessors 容器
registerBeanPostProcessors(beanFactory, orderedPostProcessors);
// Now, register all regular BeanPostProcessors.
// 再处理 没实现排序接口的
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中的 beanPostProcessors 容器
registerBeanPostProcessors(beanFactory, nonOrderedPostProcessors);
// Finally, re-register all internal BeanPostProcessors.
// 对内部的BeanPostProcessor 实例排序
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));
}
和处理BeanFactoryPostProcessor 的流程差不多, 取出所有的,按 排序接口的优先级 优先排序,实例化,然后注册到容器中。
注册 容器中:
add到 beanPostProcessors里
beanPostProcessors 就是BeanFactory实例的一个 集合 :
后续有需要用的,从该容器里拿。