1. 程式人生 > >Spring 啟動過程,bean到底是什麼時候通過反射生成例項的

Spring 啟動過程,bean到底是什麼時候通過反射生成例項的

Spring 啟動時最重要的方法refresh(),
1. 在obtainFreshBeanFactory();中建立所有物件的BeanDefinition
2. 在finishBeanFactoryInitialization(beanFactory);中建立真正的單例物件,及其依賴物件的繫結


public void refresh() throws BeansException, IllegalStateException {
        synchronized (this.startupShutdownMonitor) {

            //呼叫容器準備重新整理的方法,獲取容器的當時時間,同時給容器設定同步標識  
// Prepare this context for refreshing. prepareRefresh(); // Tell the subclass to refresh the internal bean factory. // 得到所有物件的BeanDefinition // 告訴子類啟動refreshBeanFactory()方法,Bean定義資原始檔的載入從 // 子類的refreshBeanFactory()方法啟動 ConfigurableListableBeanFactory beanFactory = obtainFreshBeanFactory(); AbstractApplicationContext.refreshBeanFactory(); AbstractApplicationContext.loadBeanDefinitions(beanFactory); AbstractXmlApplicationContext.loadBeanDefinitions(beanDefinitionReader); // 為BeanFactory配置容器特性,例如類載入器、事件處理器等
// Prepare the bean factory for use in this context. prepareBeanFactory(beanFactory); try { // 為容器的某些子類指定特殊的BeanPost事件處理器 // Allows post-processing of the bean factory in context subclasses. postProcessBeanFactory(beanFactory); // 呼叫所有註冊的BeanFactoryPostProcessor的Bean
// Invoke factory processors registered as beans in the context. invokeBeanFactoryPostProcessors(beanFactory); // 為BeanFactory註冊BeanPost事件處理器. // BeanPostProcessor是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(); // 為事件傳播器註冊事件監聽器 // Check for listener beans and register them. registerListeners(); // Instantiate all remaining (non-lazy-init) singletons. // 初始化容器內所有剩餘的單例物件,物件間的依賴關係也在此維護 finishBeanFactoryInitialization(beanFactory); beanFactory.preInstantiateSingletons(); for (String beanName : beanNames) { getBean(beanName); } // 初始化容器的生命週期事件處理器,併發布容器的生命週期事件 // Last step: publish corresponding event. finishRefresh(); } catch (BeansException ex) { // Destroy already created singletons to avoid dangling resources. destroyBeans(); // Reset 'active' flag. cancelRefresh(ex); // Propagate exception to caller. throw ex; } } }