Spring中三种后置处理器对比

BeanPostProcessor BeanFactoryPostProcessor BeanDefinitionRegistryPostProcessor
处理目标 bean 实例 BeanDefinition BeanDefinition、.class 文件等
执行时机 bena 的初始化阶段前后(已创建出 bean 对象) BeanDefinition解析完毕并注册进 BeanFactory 之后(此时 bean 未实例化) 配置文件、配置类已解析完毕并注册进 BeanFactory,但还未被 BeanFactoryPostProcessor 处理
可操作空间 对 bean 的属性赋值、创建代理对象等 给 BeanDefinition 中增删属性,移除 BeanDefinition 等 向 BeanFactory 中注册新的 BeanDefinition 和 BeanFactoryPostProcessor

BeanPostProcessor

1
2
3
4
5
6
7
8
9
10
11
12
13
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;
}

}

入参中的 bean 为根据 BeanDefinition 生成的 bean

出参中的 bean,如果不为 null 则会替换掉 BeanFactory 中传入的 bean

如果该 bean,是通过 factoryBean 生成的,则不会执行 postProcesserBeforeInitialization 方法

BeanFactoryPostProcessor

1
2
3
4
5
6
7
8
9
10
11
12
13
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;

}

通过入参 beanfactory 就可以获取到对应的 beanDefinition

BeanDefinitionRegistryPostProcessor

1
2
3
4
5
6
7
8
9
10
11
12
13
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;

}

通过 BeanDefinitionRegistryregisterBeanDefinition 方法就可以向容器中注入 beanDefinition