1. 程式人生 > >Spring Bean 的載入順序

Spring Bean 的載入順序

一,單一Bean

  • 裝載

1. 例項化; 
2. 設定屬性值; 
3. 如果實現了BeanNameAware介面,呼叫setBeanName設定Bean的ID或者Name; 
4. 如果實現BeanFactoryAware介面,呼叫setBeanFactory 設定BeanFactory; 
5. 如果實現ApplicationContextAware,呼叫setApplicationContext設定ApplicationContext 
6. 呼叫BeanPostProcessor的預先初始化方法; 
7. 呼叫InitializingBean的afterPropertiesSet()方法; 
8. 呼叫定製init-method方法; 
9. 呼叫BeanPostProcessor的後初始化方法;

  • spring容器關閉

1. 呼叫DisposableBean的destroy(); 
2. 呼叫定製的destroy-method方法;

二,多個Bean的先後順序

  • 優先載入BeanPostProcessor的實現Bean
  • 按Bean檔案和Bean的定義順序按bean的裝載順序(即使載入多個spring檔案時存在id覆蓋)
  • “設定屬性值”(第2步)時,遇到ref,則在“例項化”(第1步)之後先載入ref的id對應的bean
  • AbstractFactoryBean的子類,在第6步之後,會呼叫createInstance方法,之後會呼叫getObjectType方法
  • BeanFactoryUtils類也會改變Bean的載入順序