1. BeanPostProcessor簡(jiǎn)介
BeanPostProcessor是Spring IOC容器給我們提供的一個(gè)擴(kuò)展接口序愚。接口聲明如下:
public interface BeanPostProcessor {
//bean初始化方法調(diào)用前被調(diào)用
Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException;
//bean初始化方法調(diào)用后被調(diào)用
Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException;
}
運(yùn)行順序
===Spring IOC容器實(shí)例化Bean===
===調(diào)用BeanPostProcessor的postProcessBeforeInitialization方法===
===調(diào)用bean實(shí)例的初始化方法===
===調(diào)用BeanPostProcessor的postProcessAfterInitialization方法===
2. BeanPostProcessor實(shí)例
/**
* 后置處理器:初始化前后進(jìn)行處理工作
* 將后置處理器加入到容器中
*/
@Component
public class MyBeanPostProcessor implements BeanPostProcessor {
@Override
public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
// TODO Auto-generated method stub
System.out.println("postProcessBeforeInitialization..."+beanName+"=>"+bean);
return bean;
}
@Override
public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
// TODO Auto-generated method stub
System.out.println("postProcessAfterInitialization..."+beanName+"=>"+bean);
return bean;
}
}
3. BeanFactoryPostProcessor簡(jiǎn)介
bean工廠的bean屬性處理容器杏糙,說(shuō)通俗一些就是可以管理我們的bean工廠內(nèi)所有的beandefinition(未實(shí)例化)數(shù)據(jù)泪掀,可以隨心所欲的修改屬性。
4. BeanFactoryPostProcessor實(shí)例
@Component
public class MyBeanFactoryPostProcessor implements BeanFactoryPostProcessor {
@Override
public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {
System.out.println("MyBeanFactoryPostProcessor...postProcessBeanFactory...");
int count = beanFactory.getBeanDefinitionCount();
String[] names = beanFactory.getBeanDefinitionNames();
System.out.println("當(dāng)前BeanFactory中有"+count+" 個(gè)Bean");
System.out.println(Arrays.asList(names));
}
}
區(qū)別:
注冊(cè)BeanFactoryPostProcessor的實(shí)例,需要重載
void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException;
通過(guò)beanFactory可以獲取bean的示例或定義等。同時(shí)可以修改bean的屬性,這是和BeanPostProcessor最大的區(qū)別拴泌。
作者:xbmchina
鏈接:http://www.reibang.com/p/369a54201943
來(lái)源:簡(jiǎn)書(shū)
著作權(quán)歸作者所有。商業(yè)轉(zhuǎn)載請(qǐng)聯(lián)系作者獲得授權(quán)惊橱,非商業(yè)轉(zhuǎn)載請(qǐng)注明出處蚪腐。