Spring扩展原理1_BeanFactoryPostProcessor
BeanPostProcessor:Bean的后置处理器,bean创建对象初始化后进行拦截工作
BeanFactoryPostProcessor:beanFactory的后置处理器,在BeanFactory标准初始化(所有的beanDefinition已被保存加载到beanFactory,但是bean的实例还未被创建)之后调用
¶Demo演示
定义自己的BeanFactoryPostProcessor,并将它添加到容器中:
@Component
public class MyBeanFactoryPostProcessor implements BeanFactoryPostProcessor {
@Override
public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {
System.out.println("MyBeanFactoryPostProcessor...execute postProcessBeanFactory ...");
String[] names = beanFactory.getBeanDefinitionNames();
int count = beanFactory.getBeanDefinitionCount();
System.out.println("当前beanFactory中有"+count+"个bean");
System.out.println(Arrays.asList(names));
}
}
@ComponentScan("com.study.ext")
@Configuration
public class ExtConfig {
//随便加上几个以前写的组件,方便查看先后顺序
@Bean
public Blue blue(){
return new Blue();
}
@Bean
public Yellow Yellow(){
return new Yellow();
}
}
public class Blue {
public Blue(){
System.out.println("Blue constructor working...");
}
}
//...Yellow与Blue同
测试:
public class Test_EXT {
@Test
public void test(){
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(ExtConfig.class);
context.close();
}
}
证明BeanFactoryPostProcessor的方法postProcessBeanFactory被调用时,容器中只有BeanDefinition,Bean实例并未被创建。
- ioc容器创建对象
- invokeBeanFactoryPostProcessor( beanFactory ); 执行BeanPostProcessor
转载请注明来源,欢迎对文章中的引用来源进行考证,欢迎指出任何有错误或不够清晰的表达,邮件至 708801794@qq.com
文章标题:Spring扩展原理1_BeanFactoryPostProcessor
文章字数:246
本文作者:梅罢葛
发布时间:2020-04-08, 13:34:44
最后更新:2020-04-08, 15:21:49
原始链接:https://qiurungeng.github.io/2020/04/08/Spring%E6%89%A9%E5%B1%95%E5%8E%9F%E7%90%861-BeanFactoryPostProcessor/