Spring的refresh()方法調用過程 refresh()是Spring中比較核心的方法,Spring所有的初始化都在這個方法中完成
具體代碼如下
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) { 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; } } }Spring中refresh調用過程
//準備工作包括設定啟動時間,是否啟用標識位,初始化屬性源(property source)配置
prepareRefresh();
//建立beanFactory(過程是根據xml為每個bean產生BeanDefinition並註冊到產生的beanFactory)
ConfigurableListableBeanFactory beanFactory = obtainFreshBeanFactory();
//準備建立好的beanFactory(給beanFactory設定ClassLoader,設定SpEL運算式解析器,設定類型轉化器【能將xml String類型轉成相應對象】,增加內建ApplicationContextAwareProcessor對象,忽略各種Aware對象,註冊各種內建的對賬對象【BeanFactory,ApplicationContext】等,註冊AOP相關的一些東西,註冊環境相關的一些bean
prepareBeanFactory(ConfigurableListableBeanFactory beanFactory)
//執行個體化並調用BeanFactory中擴充了BeanFactoryPostProcessor的Bean的postProcessBeanFactory方法
invokeBeanFactoryPostProcessors(beanFactory);
//執行個體化和註冊beanFactory中擴充了BeanPostProcessor的bean
registerBeanPostProcessors(beanFactory)方法;
//執行個體化,註冊和設定國際化工具類MessageSource
initMessageSource();
//執行個體化,註冊和設定訊息廣播類(如果沒有自己定義使用預設的SimpleApplicationEventMulticaster實現,此廣播使用同步的通知方式)
initApplicationEventMulticaster();
//設定樣式工具ThemeSource
onRefresh();
//添加使用者定義的訊息接收器到上面設定的訊息廣播ApplicationEventMulticaster
registerListeners();
//設定自訂的類型轉化器ConversionService,設定自訂AOP相關的類LoadTimeWeaverAware,清除臨時的ClassLoader,凍結配置(沒看明白乾什麼的),執行個體化所有的類(懶載入的類除外)
finishBeanFactoryInitialization(ConfigurableListableBeanFactory beanFactory);
//註冊和設定跟bean生命週期相關的類(預設使用DefaultLifecycleProcessor),調用擴充了SmartLifecycle介面的start方法,使用上註冊的廣播類訊息廣播類ApplicationEventMulticaster廣播ContextRefreshedEvent事件
finishRefresh();