1 概述
有时希望在Spring IoC容器初始化受管Bean前、属性设置后对该Bean先做一些预处理,或者在容器销毁受管Bean之前自己释放资源。Spring IoC为提供了多种方法来实现受管Bean的预处理和后处理。Spring中定义了BeanPostProcessors接口:
package org.springframework.beans.factory.config;
import org.springframework.beans.BeansException;
public interface BeanPostProcessor {
Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException;
Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException;
}
若这个接口的某个实现类被注册到某个容器,那么该容器的每个受管Bean在调用初始化方法前,都会获得该接口实现类的一个回调。容器调用接口定义的方法时会将该受管Bean的实例和名字通过参数传入方法,进过处理后通过方法的返回值返回给容器。根据这个原理就可以很轻松的自定义受管Bean。要使用BeanPostProcessor回调,就必须先在容器中注册实现该接口的类。BeanFactory和ApplicationContext容器的注册方式是不一样的:若使用BeanFactory,则必须要显示的调用其addBeanPostProcessor()方法进行注册。若使用ApplicationContext,那么容器会在配置文件在中自动寻找实现了BeanPostProcessor接口的Bean,然后自动注册。
若使用了多个的BeanPostProcessor的实现类,只要实现Ordered接口,设置order属性就可以确定不同实现类的处理顺序了。
2 示例
<bean>
<bean id="stuBean" class="com.xy.test.Student">
<property name="id" value="100" />
<property name="name" value="xy" />
</bean>
<bean id="myBeanPost" class="com.xy.test.MyBeanPost" />
</beans>
public class Student {
private Integer id;
private String name;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
public String toString() {
return "Student [id=" + id + ", name=" + name + "]";
}
}
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanPostProcessor;
public class MyBeanPost implements BeanPostProcessor {
// Bean实例化前执行该方法
public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
return bean;
}
// Bean实例化后执行该方法
public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
System.out.println("postProcessAfterInitialization start,param bean is:" + bean + ",beanName:" + beanName);
if (bean instanceof Student) {
Student stu = new Student();
stu.setId(101);
stu.setName("xy1");
return stu;
}
return bean;
}
}
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class TestBean {
@SuppressWarnings("resource")
public static void main(String[] args) {
ApplicationContext ac = new ClassPathXmlApplicationContext("applicationContext.xml");
Student stu = (Student) ac.getBean("stuBean");
System.out.println(stu.toString());
}
}
运行结果:postProcessAfterInitialization start,param bean is:Student [id=100, name=xy],beanName:stuBean
Student [id=101, name=xy1]
原贴地址:http://winneryj.iteye.com/blog/307736