1. 程式人生 > >Spring IOC容器啟動過程

Spring IOC容器啟動過程

IOC容器啟動過程

  1. 資源定位(classpath,filesystem等)
  2. 載入,將bean定義轉換為內部資料結構BeanDefintion
  3. 向IOC容器註冊bean

資源定位

定位配置檔案,通過BeadDefinetionReader讀入配置

refresh方法實現

IOC容器啟動方法是ConfigurableApplicationContext中定義的refresh方法,在AbstractApplicationContext中實現

//準備階段做的是:標記容器為active狀態,以及檢查當前的執行環境,比如使用log4j,還是jdklog等
prepareRefresh();

//建立beanfactory, 定位資源,載入,裝配beandefinetion
// Tell the subclass to refresh the internal bean factory. ConfigurableListableBeanFactory beanFactory = obtainFreshBeanFactory(); //初始化beanfactory, 設定contex的classloader // Prepare the bean factory for use in this context. prepareBeanFactory(beanFactory); try { //在基本的初始化之後,對beanfactory做一些修改 // Allows post-processing of the bean factory in context subclasses.
postProcessBeanFactory(beanFactory); //呼叫beanfactory後處理器 // Invoke factory processors registered as beans in the context. invokeBeanFactoryPostProcessors(beanFactory); //註冊bean後處理器 // Register bean processors that intercept bean creation. registerBeanPostProcessors(beanFactory); //初始化訊息資源,國際化
// Initialize message source for this context. initMessageSource(); // Initialize event multicaster for this context. initApplicationEventMulticaster(); //在例項化bean之前,做一些工作 // Initialize other special beans in specific context subclasses. onRefresh(); //註冊 ApplicationListener監聽器 // Check for listener beans and register them. registerListeners(); //例項化bean // Instantiate all remaining (non-lazy-init) singletons. finishBeanFactoryInitialization(beanFactory); //釋出bean正常響應事件,初始化bean生命週期處理器 // Last step: publish corresponding event. finishRefresh(); }

BeanDefinetion

BeanDefinetion是定義bean的抽象

向IOC容器註冊BeanDefinetion

用HashMap維護BeanDefinetion, beanName作為key,BeanDefintion作為value
如果有同名key,如果有配置overridebean,那就覆蓋,沒有就報錯
populateBean方法完成bean的依賴注入

依賴注入

// Instantiate all remaining (non-lazy-init) singletons.
//在refresh方法中初始化非懶載入的bean
finishBeanFactoryInitialization(beanFactory);