前言
前面介绍 Spring 的基石:BeanDefinition。以及 BeanDefinition 的管理者:BeanFactory,还有一个 BeanDefinition 注册接口:BeanDefinitionRegistry。
这些相当于工具,那谁来操作这些工具呢?
幕后的操作者就是 Spring 中后置处理器(PostProcessor)。
后置处理器分为两种:BeanFactoryPostProcessor(Bean 工厂后置处理器) 和 BeanPostProcessor(Bean 后置处理器)
下面简述一下它们的作用
BeanFactoryPostProcessor接口
Factory hook that allows for custom modification of an application context's bean definitions, adapting the bean property values of the context's underlying bean factory.
public interface BeanFactoryPostProcessor {
/**
* Modify the application context's internal bean factory after its standard
* initialization. All bean definitions will have been loaded, but no beans
* will have been instantiated yet. This allows for overriding or adding
* properties even to eager-initializing beans.
* @param beanFactory the bean factory used by the application context
* @throws org.springframework.beans.BeansException in case of errors
*/
void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException;
}
BeanFactoryPostProcessor 接口里面只有一个 postProcessBeanFactory 方法,结合接口的注释和接口里的方法注释,可以得出,这个接口是一个 BeanFactory 钩子接口,实现该接口,可以通过 postProcessBeanFactory 方法在 BeanFactory 实例化后,Bean 实例化前调用该接口,对 BeanFactory 中的 BeanDefinition 或 BeanDefinition 的元数据进行修改。
BeanDefinitionRegistryPostProcessor
Extension to the standard BeanFactoryPostProcessor SPI, allowing for the registration of further bean definitions before regular BeanFactoryPostProcessor detection kicks in.
public interface BeanDefinitionRegistryPostProcessor extends BeanFactoryPostProcessor {
/**
* Modify the application context's internal bean definition registry after its
* standard initialization. All regular bean definitions will have been loaded,
* but no beans will have been instantiated yet. This allows for adding further
* bean definitions before the next post-processing phase kicks in.
* @param registry the bean definition registry used by the application context
* @throws org.springframework.beans.BeansException in case of errors
*/
void postProcessBeanDefinitionRegistry(BeanDefinitionRegistry registry) throws BeansException;
}
BeanDefinitionRegistryPostProcessor 继承了 BeanFactoryPostProcessor,在 Bean 实例化和检测之前,实现了一个非常重要的功能,动态注册一个 BeanDefinition,除此之外,你还可以修改已注册的 BeanDefinition 信息。
BeanPostProcessor
Factory hook that allows for custom modification of new bean instances —for example, checking for marker interfaces or wrapping beans with proxies.
public interface BeanPostProcessor {
@Nullable
default Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
return bean;
}
@Nullable
default Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
return bean;
}
}
BeanPostProcessor 是 Bean 后置处理器接口,里面包含两个方法:postProcessBeforeInitialization 和 postProcessAfterInitialization。前者在 Bean 实例化前调用,后者则是在实例化后。比如生成一个 Bean 的代理类,就是其子类做的。
总结
别小看上面三个接口,Spring 绝大部分重要技术都是这三个接口的子类来实现,它们也是扩展接口,可以自定义类来实现它们,以增强 Spring 功能或者是扩展 Spring 功能,又或是第三方框架。