概述
顾名思义, 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;
}

本文详细解析了Spring框架中的BeanPostProcessor接口,包括其作用、执行时机及具体实现流程。BeanPostProcessor允许在Bean初始化前后进行定制化的操作,是Spring容器强大的扩展点之一。
1615

被折叠的 条评论
为什么被折叠?



