Spring提供了特殊的Bean,通过配置后处理Bean对Bean进行后处理;从外部配置文件中加载配置信息;从属性文件中加载文本信息,包括国际化信息;监听并处理由其他Bean以及Spring容器发布的系统消息等。
Spring提供了一类Bean,并不对外部提供服务,无需id属性,但它负责对容器中其他的bean进行处理,例如为容器中的目标Bean生成代理。这种bean可称为bean的后处理器,在bean实例创建后,对其做进一步的处理。后处理bean主要通过bean后处理器来实现。
后处理在bean实例化以及装配完成之后发生。在bean创建及装配后,BeanPostProcessor接口提供两次修改bean的机会,Bean后处理器必须实现BeanPostProcessor接口及其两个方法:
Object postProcessBeforInitialization(Object bean,String beanName)该方式在Bean初始化(即调用afterPropertiesSet()方法及Bean指定的init-method()方法)之前调用,
Object postProcessAfterInitialization(Object bean, String beanName)该方法在bean初始化之后立即调用。
在BeanFactory中使用后处理器:
public class BeanTest {
public static void main(String[] args) {
Resource resPath = new ClassPathResource("bean.xml");
XmlBeanFactory fact = new XmlBeanFactory(resPath);
MyBeanPostProcessor processor = new MyBeanPostProcessor();
factory.addBeanPostProcessor(porcessor);// 注册后处理器
factory.getBean("Test");
}
}
容器中一旦注册了Bean后处理器,bean后处理器就会自动启动,在容器中每个bean创建时自动工作。
采用beanFactory作为容器时,必须手动注册BeanPostProcessor。
在ApplicationContext中使用后处理器:
public class BeanTest {
public static void main(String[] args) {
Resource resPath = new ClassPathResource("bean.xml");
ApplicationContext fact = new ClassPathXmlApplicationContext(resPath);
factory.getBean("Test");
}
}
采用ApplicationContext作为容器时,必须手动注册BeanPostProcessor。
后处理Bean工厂:
容器后处理器在容器实例化结束后,对容器进行额外的处理,也就是后处理bean工厂。
容器后处理器必须实现BeanFactoryPostProcessor接口。
ApplicationContext会自动检测并注册BeanFactoryPostProcessor,BeanFactory作为容器时,手动注册容器后处理器需要借助一些配置器,他们也是容器后处理器,主要包括两种:PropertyPlaceholderConfigurer,PropertyOverrideConfigurer属性占位符配置器。