16、生命周期-BeanPostProcessor原理
16.1 打断点运行postProcessBeforeInitialization
可以看到先执行的顺序为:
- applyBeanPostProcessorsBeforeInitialization
- invokeInitMethods
- applyBeanPostProcessorsAfterInitialization
16.2 BeanPostProcessor原理
- 遍历得到容器中所有的BeanPostProcessor ,挨个执行 postProcessBeforeInitialization,一旦返回null,跳出for循环,不会执行后面的BeanPostProcessor
populateBean() 给bean进行属性赋值
initializeBean(){
applyBeanPostProcessorsBeforeInitialization();
invokeInitMethods(); // 执行自定义初始化
applyBeanPostProcessorsAfterInitialization();
}
@Override
public Object applyBeanPostProcessorsBeforeInitialization(Object existingBean, String beanName)
throws BeansException {
Object result = existingBean;
for (BeanPostProcessor processor : getBeanPostProcessors()) {
Object current = processor.postProcessBeforeInitialization(result, beanName);
if (current == null) {
return result;
}
result = current;
}
return result;
}