1. 程式人生 > >spring容器初始化bean的過程中的時間週期

spring容器初始化bean的過程中的時間週期

知識點介紹

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伺服器,初始化資訊如下: