看官,直接先上个例子。
其中定义了init、destroy、afterPropertiesSet函数。
public class HelloWorld implements InitializingBean {
String message;
public String getMessage() {return message;}
public void setMessage(String message) {this.message = message;}
public void init(){System.out.println("helloworld init函数");}
public void destroy(){System.out.println("helloworld destroy函数");}
public void afterPropertiesSet() throws Exception {
System.out.println("helloworld afterPropertiesSet");
}
}
我在xml配置文件里面设置了init和destroy函数。
<bean id="helloworld" class="com.learn.helloworld.HelloWorld"
init-method="init" destroy-method="destroy">
注册每一个bean生命周期的钩子。
<bean class="com.learn.helloworld.InitHelloWorld"/>
相应的处理函数定义在了这里。
public class InitHelloWorld implements BeanPostProcessor{
public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
System.out.println("postProcessBeforeInitialization:"+beanName);
return bean;
}
public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
System.out.println("postProcessAfterInitialization:"+beanName);
return bean;
}
}
最后,运行的结果是这样的。
分析
可以看到,创建的时候,函数的运行顺序是这样的
postProcessBeforeInitialization(初始化之前) -> afterPropertiesSet(属性设置好) -> init(初始化函数) -> postProcessAfterInitialization(初始化之后)
其次,BeanPostProcessor类对每个bean都钩。所以,钩完bean再钩下一个。