@ghimi
2018-10-14T13:27:25.000000Z
字数 2773
阅读 1049
未分类
<bean id="TestBean" class="nju.software.xkxt.util.TestBean" init-method="init"></bean>
总之,afterPropertiesSet 和 inti-method 之间的执行顺序是 afterPropertiesSet 先执行,init-method 后执行.从 BeanPostProcessor 的作用,可以看出最先执行的是 postProcessBeforeInitialization ,然后是 postProcessAfterInitialization.
package nju.software.xkxt.util;import org.springframework.beans.BeansException;import org.springframework.beans.factory.config.BeanPostProcessor;/*** 定义Bean初始化前后的动作** @author typ**/public class PostProcessor implements BeanPostProcessor {@Overridepublic Object postProcessBeforeInitialization(Object bean, String beanName)throws BeansException {System.out.println("------------------------------");System.out.println("对象" + beanName + "开始实例化");return bean;}@Overridepublic Object postProcessAfterInitialization(Object bean, String beanName)throws BeansException {System.out.println("对象" + beanName + "实例化完成");System.out.println("------------------------------");return bean;}}
该PostProcessor类要作为bean定义到applicationContext.xml中,如下
<bean class="nju.software.xkxt.util.PostProcessor"></bean>
2、TestBean类,用做测试Bean,观察该Bean初始化过程中上面4个方法执行的先后顺序和内容。实现InitializingBean接口,并且实现接口中的afterPropertiesSet方法。最后定义作为init-method的init方法。
package nju.software.xkxt.util;import org.springframework.beans.factory.InitializingBean;/*** 用做测试Bean,观察该Bean初始化过程中上面4个方法执行的先后顺序和内容** @author typ**/public class TestBean implements InitializingBean {String name;public String getName() {return name;}public void setName(String name) {this.name = name;}public void init() {System.out.println("init-method is called");System.out.println("******************************");}@Overridepublic void afterPropertiesSet() throws Exception {System.out.println("******************************");System.out.println("afterPropertiesSet is called");System.out.println("******************************");}}
启动Tomcat服务器,可以看到服务器启动过程中,完成对Bean进行初始化。执行结果如下:
------------------------------对象TestBean开始实例化******************************afterPropertiesSet is called******************************init-method is called******************************对象TestBean实例化完成------------------------------