知识点介绍
1、 init-method方法,初始化bean的时候执行,可以针对某个具体的bean进行配置。init-method需要在 applicationContext.xml配置文档中bean的定义里头写明。例如:<bean id="TestBean" class="nju.software.xkxt.util.TestBean" init-method="init"></bean>
这样,当TestBean在初始化的时候会执行TestBean中定义的init方法。
2、 afterPropertiesSet方法,初始化bean的时候执行,可以针对某个具体的bean进行配置。afterPropertiesSet 必须实现 InitializingBean接口。实现 InitializingBean接口必须实现afterPropertiesSet方法。
3、 BeanPostProcessor,针对所有Spring上下文中所有的bean,可以在配置文档applicationContext.xml中配置 一个BeanPostProcessor,然后对所有的bean进行一个初始化之前和之后的代理。BeanPostProcessor接口中有两个方法: postProcessBeforeInitialization和postProcessAfterInitialization。 postProcessBeforeInitialization方法在bean初始化之前执行, postProcessAfterInitialization方法在bean初始化之后执行。
总 之,afterPropertiesSet 和init-method之间的执行顺序是afterPropertiesSet 先执行,init-method 后执行。从BeanPostProcessor的作用,可以看出最先执行的是postProcessBeforeInitialization,然后是 afterPropertiesSet,然后是init-method,然后是postProcessAfterInitialization。
相关测试示例:
1、PostProcessor类,实现BeanPostProcessor接口,实现接口中的postProcessBeforeInitialization,postProcessAfterInitialization方法
<bean id="postProcessor11" class="com.dongao.mobile.controller.activity.postProcessor"></bean>
2、TestBean类,用做测试Bean,观察该Bean初始化过程中上面4个方法执行的先后顺序和内容。实现InitializingBean接口,并且实现接口中的afterPropertiesSet方法。
3、最后定义一个设置init-method的init方法。
<bean id="wxMpServiceExt" class="com.dongao.mobile.service.base.impl.WxMpServiceExt" scope="singleton" init-method="init" />
4、部署项目后,启动tomcat服务器,初始化信息如下:
http://blog.csdn.net/glory1234work2115/article/details/51815911