BeanPostProcessor原理学习
《Spring源码解析》笔记
1、自定义的BeanPostProcessor
@Component public class MyBeanPostProcessor implements BeanPostProcessor { @Override public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException { // TODO Auto-generated method stub System.out.println("postProcessBeforeInitialization..."+beanName+"=>"+bean); return bean; } @Override public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException { // TODO Auto-generated method stub System.out.println("postProcessAfterInitialization..."+beanName+"=>"+bean); return bean; } }
2、其中postProcessBeforeInitialization函数的调用链如下:
在容器启动的时候:refresh()-->finishBeanFactoryInitialization(beanFactory)-->beanFactory.preInstantiateSingletons()->this.getBean(beanName)-->
this.doGetBean(name, (Class)null, (Object[])null, false)--this.getSingleton(beanName, new ObjectFactory<Object>()-->
singletonFactory.getObject()-->AbstractBeanFactory.this.createBean(beanName, mbd, args)-->this.doCreateBean(beanName, mbdToUse, args)
-->this.initializeBean(beanName, exposedObject, mbd)
在initializeBean()执行之前,首先执行的是populateBean()函数,该函数主要是为Bean的各个属性赋值。
this.populateBean(beanName, mbd, instanceWrapper); if (exposedObject != null) { exposedObject = this.initializeBean(beanName, exposedObject, mbd); }
3、在initializeBean(beanName, exposedObject, mbd) 中观察调用的代码
if (mbd == null || !mbd.isSynthetic()) { wrappedBean = this.applyBeanPostProcessorsBeforeInitialization(bean, beanName); } //初始化方法执行代码 try { this.invokeInitMethods(beanName, wrappedBean, mbd); } catch (Throwable var6) { throw new BeanCreationException(mbd != null ? mbd.getResourceDescription() : null, beanName, "Invocation of init method failed", var6); } if (mbd == null || !mbd.isSynthetic()) { wrappedBean = this.applyBeanPostProcessorsAfterInitialization(wrappedBean, beanName); }
4、查看applyBeanPostProcessorsBeforeInitialization和applyBeanPostProcessorsAfterInitialization函数代码
遍历得到容器中所有的BeanPostProcessor;挨个执行beforeInitialization,一但返回null,跳出for循环,不会执行后面的BeanPostProcessor.postProcessorsBeforeInitialization
对于容器中每一个Bean实例,只要符合步骤3中if语句条件,都会执行这两个函数,并不是实现BeanPostProcessor接口才会进入这两个函数。
@Override public Object applyBeanPostProcessorsBeforeInitialization(Object existingBean, String beanName) throws BeansException { Object result = existingBean; for (BeanPostProcessor processor : getBeanPostProcessors()) { result = processor.postProcessBeforeInitialization(result, beanName); if (result == null) { return result; } } return result; } @Override public Object applyBeanPostProcessorsAfterInitialization(Object existingBean, String beanName) throws BeansException { Object result = existingBean; for (BeanPostProcessor processor : getBeanPostProcessors()) { result = processor.postProcessAfterInitialization(result, beanName); if (result == null) { return result; } } return result; }