BeanPostProcessor:Bean的后置处理器,在bean初始化前后进行处理工作。源码内容如下,该类为借口,定义了两个方法。
/**
* Apply this 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.
* @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
*/
Object postProcess**Before**Initialization(Object bean, String beanName) throws BeansException;
/**
* Apply this 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 BeanPostProcessor callbacks.
* @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
*/
Object postProcess**After**Initialization(Object bean, String beanName) throws BeansException;
由源码可知两种方法最大的不同是一个在bean初始化前(before)工作,一个在bean初始化后开始工作(after)。
上图为beanpostprocessor创建的方法调用栈
首先创建容器,并注册其配置类的信息,然后调用refresh()方法
refresh()方法介绍如图上面说(加载或刷新配置的持久表示,可能是XML文件、属性文件或关系数据库架构。由于这是一个启动方法,如果失败,它应该销毁已经创建的singletone,以避免悬空的资源。换句话说,在调用该方法之后,要么全部实例化,要么根本不实例化。)
调用里面的finishBeanFactoryInitialization()方法
这个方法的作用就是实例化所有非懒汉式单实例。
待续