上一章中講解了:BeanPostProcessorFactory方法的調(diào)用洁桌,給BeanFactory中引入類BeanPostProcessor類炒瘟。這一章破喻,我們來看看spring容器在創(chuàng)建時渗稍,如何添加BeanPostProcessor。
1. registerBeanPostProcessors:注冊BeanPostProcessor到容器
public static void registerBeanPostProcessors( ConfigurableListableBeanFactory beanFactory, AbstractApplicationContext applicationContext) {
//獲取BeanFactory中的BeanPostProcessor類
String[] postProcessorNames = beanFactory.getBeanNamesForType(BeanPostProcessor.class, true, false);
//添加了BeanPostProcessorChecker
beanFactory.addBeanPostProcessor(new BeanPostProcessorChecker(beanFactory, beanProcessorTargetCount));
//將BeanPostProcessor按照PriorityOrdered->Orderd->Normal順序來整理BeanPostProcessor
List<BeanPostProcessor> priorityOrderedPostProcessors = new ArrayList<BeanPostProcessor>();
List<BeanPostProcessor> internalPostProcessors = new ArrayList<BeanPostProcessor>();
List<String> orderedPostProcessorNames = new ArrayList<String>();
List<String> nonOrderedPostProcessorNames = new ArrayList<String>();
...
// 首先排序PriorityOrdered的BeanPostProcessor菲盾,然后注冊到BeanFactory中
sortPostProcessors(beanFactory, priorityOrderedPostProcessors);
registerBeanPostProcessors(beanFactory, priorityOrderedPostProcessors);
// 接下來是Ordered->normal->internal
//最后添加了ApplicationListenerDetector的BeanPostProcessor
beanFactory.addBeanPostProcessor(new ApplicationListenerDetector(applicationContext));
}
2. addBeanPostProcessor
將BeanPostProcessor存放在List中,以備后續(xù)創(chuàng)建Bean時使用各淀。
@Override
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;
}
}