根据Bean的生命周期中Spring创建Bean的过程,可知需要实现BeanPostProcessor接口
首先创建一个测试用的类Car,并设置构造器方法,初始化方法
public class Car {
public Car(){
System.out.println("构造器...");
}
public void init(){
System.out.println("初始化...");
}
public void drive(){
System.out.println("开车...");
}
}
然后实现BeanPostProcessor接口
postProcessBeforeInitialization方法是bean初始化之前的操作
postProcessAfterInitialization方法是bean初始化之后的操作
public class MyPostProcessor implements BeanPostProcessor {
public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
System.out.println("初始化前的操作。。。。");
return bean;//返回该bean,因为拿出来处理之后要放回Ioc容器
}
public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
System.out.println("初始化后的操作。。。。");
return bean;
}
}
且需要将这个实现了BeanPostProcessor接口的类交给spring管理,对于ApplicationContex来说,会自动识别bean实现了BeanPostProcessor接口,并注册为后置处理器。而对于BeanFactory来说,则需要手动指定该bean的id为postProcessor
<bean id="car" class="Car" init-method="init"/>
<bean class="MyPostProcessor"/>
测试一下:
public class APP {
public static void main(String args[]) {
ClassPathXmlApplicationContext contex=new ClassPathXmlApplicationContext("applicationContext.xml");
Car car = (Car)contex.getBean("car");
car.drive();
}
}
结果:
注意:该接口的实现类针对所有的bean初始化过程,如果想区别对待,可以对BeanPostProcessor方法中的beanName做一些判断