bean初始化有三種方法:
- 使用方法上加@PostConstruct
- 類實作InitializingBean接口,重寫AfterPropertiesSet方法
- 通過 元素的 init-method屬性配置
且順序依次是1->2->3
示例:
public class InitSequenceDemoBean implements InitializingBean {
public InitSequenceDemoBean() {
System.out.println("InitSequenceBean: constructor");
}
@PostConstruct
public void postConstruct() {
System.out.println("InitSequenceBean: postConstruct");
}
public void initMethod() {
System.out.println("InitSequenceBean: init-method");
}
@Override
public void afterPropertiesSet() throws Exception {
System.out.println("InitSequenceBean: afterPropertiesSet");
}
}
配置檔案中添加如下Bean定義:
<bean class="InitSequenceDemoBean"
init-method="initMethod"></bean>
輸出結果:
InitSequenceBean: constructor
InitSequenceBean: postConstruct
InitSequenceBean: afterPropertiesSet
InitSequenceBean: init-method
通過上述輸出結果,說明三種初始化的順序是:
Constructor > @PostConstruct > InitializingBean > init-method
bean的生命周期如下:
1)設定屬性值;
2)如果該Bean實作了BeanNameAware接口,調用Bean中的BeanNameAware.setBeanName()方法
3)如果該Bean實作了BeanFactoryAware接口,調用Bean中的BeanFactoryAware.setBeanFactory()方法
4)如果該Bean實作了ApplicationContextAware接口,
調用bean中setApplicationContext()方法
5)如果該Bean實作了BeanPostProcessor接口,調用BeanPostProcessors.postProcessBeforeInitialization()方法;@PostConstruct注解後的方法就是在這裡被執行的
6)如果該Bean實作了InitializingBean接口,調用Bean中的afterPropertiesSet方法
7)如果在配置bean的時候指定了init-method,例如: 調用Bean中的init-method
8)如果該Bean實作了BeanPostProcessor接口,調用BeanPostProcessors.postProcessAfterInitialization()方法;
9)如果該Bean是單例的,則當容器銷毀并且該Bean實作了DisposableBean接口的時候,調用destory方法;如果該Bean是prototype,則将準備好的Bean送出給調用者,後續不再管理該Bean的生命周期。