一.BeanPostProcessor
在Bean初始化前后,由Spring回调,可以在Bean的实例化、配置和其他的初始化前后添加一些自己的逻辑处理。
public interface BeanPostProcessor {
/**
* 在任何初始化代码(比如配置文件中的init-method)调用之前调用。
*/
Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException;
/**
* 实例化之后进行处理
*/
Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException;
}
注意:
1. ApplicationContext会自动检测在配置文件中实现了BeanPostProcessor接口的所有bean。并把他们注册为后置处理器,然后在容器创建bean的适当时候调用它。因此部署一个后置处理器同部署其他bean并没有什么区别。
<bean class="TestBeanPostProcessor" />
2.而使用BeanFactory实现的时候,bean后置处理器必须通过代码显式的去注册,在IOC容器集成体系中ConfingurableBeanFactory接口中定义了注册方法。
TestBeanPostPrcessor beanPostProcessor = new TestBeanPostPrcessor();
Resource resource = new FileSystemResource("applicationContext.xml");
ConfigurableBeanFactory factory = new XmlBeanFactory(resource);
factory.addBeanPostProcessor(beanPostProcessor);
factory.getBean("logic");
二.BeanFactoryPostProcessor
与BeanPostProcessor接口类似,可以对bean的定义进行处理
public interface BeanFactoryPostProcessor {
/**
* 在所有bean的配置加载完毕,任何一个bean创建之前调用
*/
void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException;
}
典型的BeanFactoryPostProcessor是PropertyPlaceholderConfigurer,它间接继承了BeanFactory,在bean工厂加载了所有bean的配置之后,spring就会调用postProcessBeanFactory方法,去读取所有的.property文件并将其中的配置转化为对相应的类型告知BeanFactory。
/**
* PropertyPlaceholderConfigurer-->PlaceholderConfigurerSupport-->
* PropertyResourceConfigurer-->BeanFactoryPostProcessor
*/
@Override
public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {
try {
Properties mergedProps = mergeProperties();
// Convert the merged properties, if necessary.
convertProperties(mergedProps);
// Let the subclass process the properties.
processProperties(beanFactory, mergedProps);
}
catch (IOException ex) {
throw new BeanInitializationException("Could not load properties", ex);
}
}
只有通过ApplicationContext管理bean时BeanFactoryPostProcessor才会有作用,ApplicationContext会自动检测在配置文件中实现了BeanFactoryPostProcessor接口的所有bean,并存放在beanFactoryPostProcessors中。