前面我們學(xué)習(xí)了Spring注解版的聲明式事務(wù)和Aop功能的開發(fā)及相關(guān)源碼解讀,其實(shí)不然鹰贵,Spring還有一塊核心的知識(shí)拓展功能,這里包括了beanFactoryPostProcessor【beanFactory的后置處理器】、BeanDefinitionRegistryPostProcessor【bean定義注冊(cè)的后置處理器】以及ApplicationListener【事件監(jiān)聽和發(fā)布】等弊添,本節(jié)我們先來學(xué)習(xí)beanFactoryPostProcessor
beanFactoryPostProcessor和BeanPostProcessor
- BeanPostProcessor
是bean的后置處理器鬼悠,在bean創(chuàng)建對(duì)象初始化前后攔截進(jìn)行工作
- BeanFactoryPostProcessor
beanFactory類型的后置處理器删性,按照官方的解釋:在beanFactory標(biāo)準(zhǔn)初始化之后來定制修改BeanFactory的內(nèi)容:此時(shí)所有bean的定義被加載進(jìn)beanFactory中亏娜,但是bean的實(shí)例未完成創(chuàng)建
demo
-1. 自定義MyBeanFactoryPostProcessor并實(shí)現(xiàn)BeanFactoryPostProcessor接口
@Component
public class MyBeanFactoryPostProcessor implements BeanFactoryPostProcessor {
@Override
public void postProcessBeanFactory(ConfigurableListableBeanFactory configurableListableBeanFactory) throws BeansException {
System.out.println("MyBeanFactoryPostProcessor ....postProcessBeanFactory ");
//當(dāng)前已經(jīng)完成初始化的beanFactory
int count = configurableListableBeanFactory.getBeanDefinitionCount();
System.out.println("當(dāng)前beanFactory中有:"+count+"個(gè)bean的定義信息,分別是如下:");
String[] names = configurableListableBeanFactory.getBeanDefinitionNames();
System.out.println(Arrays.asList(names));
}
注意一點(diǎn)別忘了添加注解Component【其主要的目的是標(biāo)記為一個(gè)組件】
- 2 配置類
@Configuration
@ComponentScan(value = "com.cacmp.bean.expand")
public class ExpandConfig {
@Bean
public Car car(){
return new Car();
}
- 3.來看測試類
//Spring拓展BeanFactoryPostProcessor的測試
@Test
public void testExpand(){
AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext(ExpandConfig.class);
applicationContext.close();
}
測試結(jié)果如下圖所示:
可以在上述的截圖中找到我們自己的定義的在beanFactory中的bean蹬挺,那么關(guān)于BeanFactoryPostProcessor簡單的案例就到這里维贺,在后續(xù)我們來深入學(xué)習(xí)其相關(guān)源碼知識(shí)