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();