概述
顾名思义, BeanPostProcessor
定义了关于Bean
的PostProcessor
。这里的Bean
就是我们一般意义上所说的bean
容器中的bean
实例了。
Spring
容器在每个bean
实例创建过程中bean
实例初始化前后调用接口BeanPostProcessor
定义的方法。
BeanPostProcessor
接口定义了两个方法:
Object postProcessBeforeInitialization(Object bean, String beanName)
Object postProcessAfterInitialization(Object bean, String beanName)
这两个方法的执行时机如下图所示 :
以上流程的具体代码可以参考
AbstractAutowireCapableBeanFactory#doCreateBean
方法实现。
上图中的bean
初始化指的是以下几种情况 :
- 通过
InitializingBean
接口实现的afterPropertiesSet()
方法; xml
方式指定的bean
的init-method
初始化方法;JSR-250
注解@PostConstruct
注解的初始化方法;Java
配置类中@Bean(initMethod = "init")
指定的初始化方法;
源代码解析
/**
*
* 对新的bean实例进行订制化修改的factory hook。
* ApplicationContexts can autodetect BeanPostProcessor beans in their
* bean definitions and apply them to any beans subsequently created.
*
* 应用程序上下文ApplicationContext能够从自己的bean定义中自动检测BeanPostProcessor bean,
* 并随后在任意bean创建时应用到新创建的bean。
*
* @author Juergen Hoeller
* @since 10.10.2003
* @see InstantiationAwareBeanPostProcessor
* @see DestructionAwareBeanPostProcessor
* @see ConfigurableBeanFactory#addBeanPostProcessor
* @see BeanFactoryPostProcessor
*/
public interface BeanPostProcessor {
/**
* @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 null, no subsequent BeanPostProcessors will be invoked
* @throws org.springframework.beans.BeansException in case of errors
* @see org.springframework.beans.factory.InitializingBean#afterPropertiesSet
*/
Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException;
/**
* 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 bean instanceof FactoryBean checks.
*
* This callback will also be invoked after a short-circuiting triggered by a
* 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 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 postProcessAfterInitialization(Object bean, String beanName) throws BeansException;
}