Spring原始碼學習筆記 (一)bean是怎麼生成的
阿新 • • 發佈:2018-12-11
bean 實在 bean 重新整理過程中產生的,首先我們看下 bean 的重新整理方法。下面是 AbstractApplicationContext 的 refresh 方法。
@Override public void refresh() throws BeansException, IllegalStateException { synchronized (this.startupShutdownMonitor) { // Prepare this context for refreshing. prepareRefresh(); // Tell the subclass to refresh the internal bean factory. ConfigurableListableBeanFactory beanFactory = obtainFreshBeanFactory(); // Prepare the bean factory for use in this context. prepareBeanFactory(beanFactory); try { // Allows post-processing of the bean factory in context subclasses. postProcessBeanFactory(beanFactory); // Invoke factory processors registered as beans in the context. invokeBeanFactoryPostProcessors(beanFactory); // Register bean processors that intercept bean creation. registerBeanPostProcessors(beanFactory); // Initialize message source for this context. initMessageSource(); // Initialize event multicaster for this context. initApplicationEventMulticaster(); // 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); // Last step: publish corresponding event. finishRefresh(); } catch (BeansException ex) { if (logger.isWarnEnabled()) { logger.warn("Exception encountered during context initialization - " + "cancelling refresh attempt: " + ex); } // Destroy already created singletons to avoid dangling resources. destroyBeans(); // Reset 'active' flag. cancelRefresh(ex); // Propagate exception to caller. throw ex; } finally { // Reset common introspection caches in Spring's core, since we // might not ever need metadata for singleton beans anymore... resetCommonCaches(); } } }
我們可以看到這個方法中一共進行了準備重新整理,獲取bean工廠,呼叫 postProcess 等一系列操作。
這裡有一個比較重要的地方就是 postProcess 是什麼東西
熟悉 spring 的應該都知道,postProcessor給 使用者留的一個擴充套件點,Spring允許BeanFactoryPostProcessor在容器例項化前後操縱 bean 的屬性,BeanPostProcessor實現類可以在bean初始化前後做一些事情,BeanPostProcessor的作用域是容器級的,它只和所在容器有關。
bean 的預設生成就是通過預設的 postProcessor 生成的。bean 的生成主要分為通過註解,通過xml,通過自動掃描,以及mybatis dao的bean生成,這些每一種型別都是一種bean的生成器,當然,我們也可以自定義我們自己的 bean 生成器。
bean 生成以後被儲存在一個map裡,用來供呼叫。
初看 spring 原始碼,難免理解錯誤,希望大家能指出和諒解,感激不盡。