1. 程式人生 > 程式設計 >Spring教程之refresh()執行邏輯淺析

Spring教程之refresh()執行邏輯淺析

前言

對於AbstractApplicationContex#refresh()方法邏輯,可所謂是貫通spring框架核心邏輯,溪源在debug過程中,理解起來也是懵懵懂懂,自己也買了《Spring原始碼深度解析》書籍學習其思想和實現邏輯,經過不斷的整理學習總結,最終誕生這篇文章,方便後面自己忘記了檢視和理解。

下面開始正式踏入refresh方法的整體概覽淺析。

概覽

refresh

該方法是 Spring Bean 載入的核心,它是 ClassPathXmlApplicationContext 的父類 AbstractApplicationContext 的一個方法 , 顧名思義,用於重新整理整個Spring 上下文資訊,定義了整個 Spring 上下文載入的流程。

先看下refresh()方法總體:

@Override
public void refresh() throws BeansException,IllegalStateException {
 synchronized (this.startupShutdownMonitor) {
 // 準備預處理:記錄容器的啟動時間startupDate,標記容器為啟用,初始化上下文環境如檔案路徑資訊,驗證必填屬性是否填寫 
 this.prepareRefresh();
 // **告訴子類去重新整理bean工廠,此方法解析配置檔案並將bean資訊儲存到beanDefinition中,註冊到BeanFactory(但是未被初始化,僅將資訊寫到了beanDefination的map中)**重點方法,下面的操作都基於這個beanFactory進行的
 ConfigurableListableBeanFactory beanFactory = this.obtainFreshBeanFactory();
 // 設定beanFactory的基本屬性:類載入器,新增多個beanPostProcesser
 this.prepareBeanFactory(beanFactory);
 try {
 // 空實現:允許子類上下文中對beanFactory做後期處理
 this.postProcessBeanFactory(beanFactory);
 /**************************以上是BeanFactory的建立及預準備工作 ****************/
 // 呼叫BeanFactoryPostProcessor各個實現類的方法
 this.invokeBeanFactoryPostProcessors(beanFactory);
 // 註冊 BeanPostProcessor 的實現類,注意看和 BeanFactoryPostProcessor 的區別
 // 此介面兩個方法: postProcessBeforeInitialization 和 postProcessAfterInitialization
 // 兩個方法分別在 Bean 初始化之前和初始化之後得到執行。注意,到這裡 Bean 還沒初始化
 this.registerBeanPostProcessors(beanFactory);
 //初始化ApplicationContext的MessageSource元件(資原始檔),如國際化檔案,訊息解析,繫結等
 this.initMessageSource();
 //初始化ApplicationContext事件廣播器
 this.initApplicationEventMulticaster();
 // 初始化子類特殊bean(鉤子方法)
 this.onRefresh();
 // 獲取所有的事件監聽器,並將監聽器註冊到事件廣播器
 this.registerListeners();
 //** 初始化所有singleton bean;**重點方法
 this.finishBeanFactoryInitialization(beanFactory);
 // 廣播事件:ApplicationContext初始化完成
 this.finishRefresh();
} catch (BeansException ex) {
	if (logger.isWarnEnabled()) {
	logger.warn("Exception encountered during context initialization - " + "cancelling refresh attempt: " + ex);
	}
		// 銷燬bean
		this.destroyBeans();
		// 重置 'active' 標誌.
		this.cancelRefresh(ex);
		throw ex;
			}
		}

明細

本篇文章,不會仔細往下探討原始碼實現邏輯,先總結refresh()方法具體邏輯:

1.prepareRefresh

準備預處理:記錄spring容器的啟動時間startupDate,標記容器為啟用,初始化上下文環境如檔案路徑資訊,驗證必填屬性是否填寫。

  • initPropertySources():初始化一些屬性設定;子類自定義個性化的屬性設定方法;
  • getEnvironment().validateRequiredProperties():檢驗屬性的合法等;
  • earlyApplicationEvents= new LinkedHashSet():儲存容器中的一些早期的事件;
//重新整理前的預處理;
protected void prepareRefresh() {
 this.startupDate = System.currentTimeMillis();
 this.closed.set(false);
 this.active.set(true);
​
 if (logger.isInfoEnabled()) {
 logger.info("Refreshing " + this);
 }
 // 初始化一些屬性設定;子類自定義個性化的屬性設定方法;
 initPropertySources(); 
 // 校驗配置檔案的屬性,合法性
 getEnvironment().validateRequiredProperties();
 //儲存容器中的一些事件
 this.earlyApplicationEvents = new LinkedHashSet<ApplicationEvent>();
}

2.obtainFreshBeanFactory

獲取BeanFactory,解析配置檔案,生成beanDefinition;

protected ConfigurableListableBeanFactory obtainFreshBeanFactory() {
 refreshBeanFactory(); //建立了一個this.beanFactory = new DefaultListableBeanFactory();設定了序列化的ID
 //返回剛才建立的DefaultListableBeanFactory
 ConfigurableListableBeanFactory beanFactory = getBeanFactory();
 if (logger.isDebugEnabled()) {
 logger.debug("Bean factory for " + getDisplayName() + ": " + beanFactory);
 }
 return beanFactory;
}

3.prepareBeanFactory

該方法主要負責對BeanFactory的預準備工作,配置beanFactory的基礎屬性,比如ClassLoader和一些PostProcessor等。
這個方法主要是給BeanFactory設定一些基本的屬性,比如類載入器、表示式解析器、屬性編輯器,註冊幾個單例、新增一些不用注入的介面、新增解析依賴項等。

  • 設定BeanFactory的類載入器、支援表示式解析器…
  • 新增部分BeanPostProcessor【ApplicationContextAwareProcessor】
  • 設定忽略的自動裝配的介面EnvironmentAware、EmbeddedValueResolverAware、xxx;
  • 註冊可以解析的自動裝配;我們能直接在任何元件中自動注入:
    BeanFactory、ResourceLoader、ApplicationEventPublisher、ApplicationContext
  • 新增BeanPostProcessor【ApplicationListenerDetector】
  • 新增編譯時的AspectJ;
  • 給BeanFactory中註冊一些能用的元件;
    environment【ConfigurableEnvironment】、
    systemProperties【Map<String,Object>】、
    systemEnvironment【Map<String,Object>】
protected void prepareBeanFactory(ConfigurableListableBeanFactory beanFactory) {
 	// Tell the internal bean factory to use the context's class loader etc.
 //設定類載入器
 	beanFactory.setBeanClassLoader(getClassLoader());
 //設定bean表示式解析器,詳解見下文
 	beanFactory.setBeanExpressionResolver(new StandardBeanExpressionResolver());
 	//資源編輯註冊器
 	beanFactory.addPropertyEditorRegistrar(new ResourceEditorRegistrar(this,getEnvironment()));

 	//新增一個BeanPostProcessor:ApplicationContextAwareProcessor,用於向實現類ApplitionContextAware中,呼叫setApplicationContext方法,並將ApplicationContext作為引數。
 	beanFactory.addBeanPostProcessor(new ApplicationContextAwareProcessor(this));
 
 	//新增忽略自動裝配的介面
 	beanFactory.ignoreDependencyInterface(EnvironmentAware.class);
 	beanFactory.ignoreDependencyInterface(EmbeddedValueResolverAware.class);
 	beanFactory.ignoreDependencyInterface(ResourceLoaderAware.class);
 	beanFactory.ignoreDependencyInterface(ApplicationEventPublisherAware.class);
 	beanFactory.ignoreDependencyInterface(MessageSourceAware.class);
 	beanFactory.ignoreDependencyInterface(ApplicationContextAware.class);
 

 	// 註冊幾個解析依賴項,意思是,當一個Bean需要注入對應的類時,使用下面註冊的這些類
 //比如,如果@Autowire 一個BeanFactory,那麼這個BeanFactory實際就是在此處註冊的一個物件
 //這幾項分別是:BeanFactory、ResourceLoader、ApplicationEventPublisher、ApplicationContext
 	beanFactory.registerResolvableDependency(BeanFactory.class,beanFactory);
 	beanFactory.registerResolvableDependency(ResourceLoader.class,this);
 	beanFactory.registerResolvableDependency(ApplicationEventPublisher.class,this);
 	beanFactory.registerResolvableDependency(ApplicationContext.class,this);

 	// Detect a LoadTimeWeaver and prepare for weaving,if found.
 	//檢查是否由LoadTimeWeaver,如果有loadTimeWeaver的bean,就放入一個BeanPostProcessor:LoadTimeWeaverAwareProcessor
 	if (beanFactory.containsBean(LOAD_TIME_WEAVER_BEAN_NAME)) {
 		beanFactory.addBeanPostProcessor(new LoadTimeWeaverAwareProcessor(beanFactory));
 		// Set a temporary ClassLoader for type matching.
 		beanFactory.setTempClassLoader(new ContextTypeMatchClassLoader(beanFactory.getBeanClassLoader()));
 	}
 	
 	// 註冊environment,註冊成單例
 	if (!beanFactory.containsLocalBean(ENVIRONMENT_BEAN_NAME)) {
 		beanFactory.registerSingleton(ENVIRONMENT_BEAN_NAME,getEnvironment());
 	}
 	 //註冊systemProperties 成單例
 	if (!beanFactory.containsLocalBean(SYSTEM_PROPERTIES_BEAN_NAME)) {
 		beanFactory.registerSingleton(SYSTEM_PROPERTIES_BEAN_NAME,getEnvironment().getSystemProperties());
 	}
 //註冊 systemEnvironment 成單例
 	if (!beanFactory.containsLocalBean(SYSTEM_ENVIRONMENT_BEAN_NAME)) {
 		beanFactory.registerSingleton(SYSTEM_ENVIRONMENT_BEAN_NAME,getEnvironment().getSystemEnvironment());
 	}
 }

4.postProcessBeanFactory

主要負責在BeanFactory準備工作完成之後,beanFactory的後置處理工作;

protected void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) {
 }

5. invokeBeanFactoryPostProcessors

protected void invokeBeanFactoryPostProcessors(ConfigurableListableBeanFactory beanFactory) {
 // Invoke BeanDefinitionRegistryPostProcessors first,if any.
 
 //用於存放已處理過的Bean
 Set<String> processedBeans = new HashSet<String>();
 
 //如果IOC容器是一個BeanDefinitionRegistry,有了註冊BeanDefinition的能力,就可以執行BeanDefinitionRegistryPostProcessor的postProcessBeanDefinitionRegistry方法
 if (beanFactory instanceof BeanDefinitionRegistry) {
 
 BeanDefinitionRegistry registry = (BeanDefinitionRegistry) beanFactory;
 
 //regularPostProcessors用於存放普通的BeanFactoryPostProcessor
 List<BeanFactoryPostProcessor> 
 regularPostProcessors = new LinkedList<BeanFactoryPostProcessor>();
 
 //registryPostProcessors用於存放 BeanDefinitionRegistryPostProcessor
 List<BeanDefinitionRegistryPostProcessor> 
 registryPostProcessors = new LinkedList<BeanDefinitionRegistryPostProcessor>();
 
 //查詢通過addBeanFactoryPostProcessor等方法設定進來的的BeanFactoryPostProcessor(不是註冊到IOC容器的中)
 for (BeanFactoryPostProcessor postProcessor : getBeanFactoryPostProcessors()) {
 
 //如果是 BeanDefinitionRegistryPostProcessor ,
 //就先執行它的postProcessBeanDefinitionRegistry,用於向IOC中註冊一些BeanDefinition,
 //然後新增到registryPostProcessors佇列中
 if (postProcessor instanceof BeanDefinitionRegistryPostProcessor) {
 BeanDefinitionRegistryPostProcessor registryPostProcessor =
  (BeanDefinitionRegistryPostProcessor) postProcessor;
				 
 	registryPostProcessor.postProcessBeanDefinitionRegistry(registry);
 registryPostProcessors.add(registryPostProcessor);
 }
 else {
 //如果是普通的BeanFactoryPostProcessor,就新增到regularPostProcessors佇列中
 regularPostProcessors.add(postProcessor);
 }
 }
 
 //獲取IOC容器中註冊的BeanDefinitionRegistryPostProcessor,
 //放入到registryPostProcessorBeans中,
 //並按照Order排序
 Map<String,BeanDefinitionRegistryPostProcessor> beanMap =
 beanFactory.getBeansOfType(BeanDefinitionRegistryPostProcessor.class,true,false);
 
 List<BeanDefinitionRegistryPostProcessor> registryPostProcessorBeans =
 new ArrayList<BeanDefinitionRegistryPostProcessor>(beanMap.values());
 
 OrderComparator.sort(registryPostProcessorBeans);
 
 //先呼叫registryPostProcessorBeans中的所有postProcessBeanDefinitionRegistry方法
 for (BeanDefinitionRegistryPostProcessor postProcessor : registryPostProcessorBeans) {
 postProcessor.postProcessBeanDefinitionRegistry(registry);
 }
 //先呼叫 registryPostProcessors中的postProcessBeanFactory方法
 //再呼叫 registryPostProcessorBeans中的postProcessBeanFactory方法
 //最後呼叫 regularPostProcessors中的postProcessBeanFactory方法
 invokeBeanFactoryPostProcessors(registryPostProcessors,beanFactory);
 invokeBeanFactoryPostProcessors(registryPostProcessorBeans,beanFactory);
 invokeBeanFactoryPostProcessors(regularPostProcessors,beanFactory);
 
 //對於IOC容器中註冊的BeanDefinitionRegistryPostProcessor來說,還要放置到processedBeans中,放置重複呼叫
 processedBeans.addAll(beanMap.keySet());
 }
 else {
 //如果IOC就是一個普通的BeanFacotry,就直接從context中取出所有的BeanFactoryPostProcessor,並呼叫他們的postProcessBeanFactory方法
 // Invoke factory processors registered with the context instance.
 invokeBeanFactoryPostProcessors(getBeanFactoryPostProcessors(),beanFactory);
 }
	
 // Do not initialize FactoryBeans here: We need to leave all regular beans
 // 查詢IOC容器中所有的BeanFactoryPostProcessor,有可能上面的BeanDefinitionRegistryPostProcessor剛剛向IOC容器中註冊了一些BeanFactoryPostProcessor,所以要在此處全部查出來。
 String[] postProcessorNames =
 beanFactory.getBeanNamesForType(BeanFactoryPostProcessor.class,false);

 // 按照 這些BeanFactoryPostProcessor實現的排序介面( PriorityOrdered 和 Ordered)分成3組
 //第一組 實現了PriorityOrdered --- priorityOrderedPostProcessors
 //第二組 實現了Ordered --- orderedPostProcessorNames
 //第三組 沒有實現排序介面 --- nonOrderedPostProcessorNames
 List<BeanFactoryPostProcessor> priorityOrderedPostProcessors = new ArrayList<BeanFactoryPostProcessor>();
 List<String> orderedPostProcessorNames = new ArrayList<String>();
 List<String> nonOrderedPostProcessorNames = new ArrayList<String>();
 
 for (String ppName : postProcessorNames) {
 //如果已經處理了,就跳過
 if (processedBeans.contains(ppName)) {
 // skip - already processed in first phase above
 }
 //實現PriorityOrdered 介面的
 else if (isTypeMatch(ppName,PriorityOrdered.class)) {
 
 priorityOrderedPostProcessors.add(beanFactory.getBean(ppName,BeanFactoryPostProcessor.class));
 }
 // 實現Ordered 介面的
 else if (isTypeMatch(ppName,Ordered.class)) {
 orderedPostProcessorNames.add(ppName);
 }
 //普通的
 else {
 nonOrderedPostProcessorNames.add(ppName);
 }
 }
 //然後先執行priorityOrderedPostProcessors中的,再執行orderedPostProcessorNames的,最後執行nonOrderedPostProcessorNames
	
 //排序並執行priorityOrderedPostProcessors的
 OrderComparator.sort(priorityOrderedPostProcessors);
 invokeBeanFactoryPostProcessors(priorityOrderedPostProcessors,beanFactory);

 // 排序並執行orderedPostProcessors的
 List<BeanFactoryPostProcessor> orderedPostProcessors = new ArrayList<BeanFactoryPostProcessor>();
 for (String postProcessorName : orderedPostProcessorNames) {
 orderedPostProcessors.add(getBean(postProcessorName,BeanFactoryPostProcessor.class));
 }
 OrderComparator.sort(orderedPostProcessors);
 invokeBeanFactoryPostProcessors(orderedPostProcessors,beanFactory);

 // 最後執行普通的BeanFactoryPostProcessor的
 List<BeanFactoryPostProcessor> nonOrderedPostProcessors = new ArrayList<BeanFactoryPostProcessor>();
 for (String postProcessorName : nonOrderedPostProcessorNames) {
 nonOrderedPostProcessors.add(getBean(postProcessorName,BeanFactoryPostProcessor.class));
 }
 invokeBeanFactoryPostProcessors(nonOrderedPostProcessors,beanFactory);
}

6.registerBeanPostProcessors

protected void registerBeanPostProcessors(ConfigurableListableBeanFactory beanFactory) {
 // 獲取IOC中註冊的 BeanPostProcessor
 String[] postProcessorNames = beanFactory.getBeanNamesForType(BeanPostProcessor.class,false);

 // BeanPostProcessorChecker 也是一個 BeanPostProcessor,用於檢查一個Bean應該經過的BeanPostProcessor和
 
 int beanProcessorTargetCount = beanFactory.getBeanPostProcessorCount() + 1 + postProcessorNames.length;
 beanFactory.addBeanPostProcessor(new BeanPostProcessorChecker(beanFactory,beanProcessorTargetCount));

 //按照排序介面分類。
 //這裡需要注意的是,priorityOrderedPostProcessors裡面裝的是BeanPostProcessor
 //而orderedPostProcessorNames和nonOrderedPostProcessorNames裡面裝的是BeanPostProcessor的name
 //原因是:例項化BeanPostProcessor實現類的時候,也需要呼叫IOC中已有的BeanPostProcessor,所以Spring這裡沒有提前例項化Orderd介面和普通的BeanPostProcessor。
 //因此,這裡有一個有趣的現象,示例化Orderd介面的BeanProcessor的時候,會使用PriorityOrdered的BeanPostProcessor進行處理
 //例項化普通的BeanProcessor時,會先後經過PriorityOrdered和Orderd介面的BeanPostProcessor的處理
 
 List<BeanPostProcessor> priorityOrderedPostProcessors = new ArrayList<BeanPostProcessor>();
 List<BeanPostProcessor> internalPostProcessors = new ArrayList<BeanPostProcessor>();
 
 List<String> orderedPostProcessorNames = new ArrayList<String>();
 List<String> nonOrderedPostProcessorNames = new ArrayList<String>();
 
 //分類
 for (String ppName : postProcessorNames) {
 //PriorityOrdered介面的,先行例項化,並把MergedBeanDefinitionPostProcessor放入到internalPostProcessors中
 if (isTypeMatch(ppName,PriorityOrdered.class)) {
 BeanPostProcessor pp = beanFactory.getBean(ppName,BeanPostProcessor.class);
 priorityOrderedPostProcessors.add(pp);
 //
 if (pp instanceof MergedBeanDefinitionPostProcessor) {
 internalPostProcessors.add(pp);
 }
 }
 //Ordered介面的,這裡只是把name記錄下來。
 else if (isTypeMatch(ppName,Ordered.class)) {
 //
 orderedPostProcessorNames.add(ppName);
 }
 //普通的,這裡只是把name記錄下來。
 else {
 nonOrderedPostProcessorNames.add(ppName);
 }
 }

 //排序並註冊PriorityOrdered介面的BeanPostProcessor
 OrderComparator.sort(priorityOrderedPostProcessors);
 registerBeanPostProcessors(beanFactory,priorityOrderedPostProcessors);

 //排序並註冊Ordered介面的BeanPostProcessor
 List<BeanPostProcessor> orderedPostProcessors = new ArrayList<BeanPostProcessor>();
 for (String ppName : orderedPostProcessorNames) {
 //這裡才進行例項化,所以會使用實現了PriorityOrdered介面的BeanPostProcessor進行處理
 BeanPostProcessor pp = beanFactory.getBean(ppName,BeanPostProcessor.class);
 orderedPostProcessors.add(pp);
 //把MergedBeanDefinitionPostProcessor放入到internalPostProcessors中
 if (pp instanceof MergedBeanDefinitionPostProcessor) {
 internalPostProcessors.add(pp);
 }
 }
 OrderComparator.sort(orderedPostProcessors);
 registerBeanPostProcessors(beanFactory,orderedPostProcessors);

 // 註冊普通的BeanPostProcessor
 List<BeanPostProcessor> nonOrderedPostProcessors = new ArrayList<BeanPostProcessor>();
 for (String ppName : nonOrderedPostProcessorNames) {
 //這裡才進行例項化,所以會使用實現了PriorityOrdered介面或Orderd的BeanPostProcessor進行處理
 BeanPostProcessor pp = beanFactory.getBean(ppName,BeanPostProcessor.class);
 nonOrderedPostProcessors.add(pp);
 //把 MergedBeanDefinitionPostProcessor 放入到internalPostProcessors中
 //同時注意到,即使在internalPostProcessors中
 //BeanPostProcessor的順序也是按照 PriorityOrderd > Orderd > 普通 的順序進入的。
 if (pp instanceof MergedBeanDefinitionPostProcessor) {
 internalPostProcessors.add(pp);
 }
 }
 registerBeanPostProcessors(beanFactory,nonOrderedPostProcessors);

 //註冊所有的MergedBeanDefinitionPostProcessor
 OrderComparator.sort(internalPostProcessors);
 registerBeanPostProcessors(beanFactory,internalPostProcessors);
	
 //最後,在末尾新增一個ApplicationListenerDetector
 beanFactory.addBeanPostProcessor(new ApplicationListenerDetector());
}

7.initMessageSource

初始化MessageSource元件(做國際化功能;訊息繫結,訊息解析);

  • 獲取BeanFactory
  • 判斷容器中是否有id為messageSource的,型別是MessageSource的元件;
    如果有賦值給messageSource,如果沒有自己建立一個DelegatingMessageSource;
    MessageSource:取出國際化配置檔案中的某個key的值;能按照區域資訊獲取;
  • 將建立完成的MessageSource註冊在容器中,以後獲取國際化配置檔案的值的時候,可以自動注入MessageSource;
protected void initMessageSource() {
 ConfigurableListableBeanFactory beanFactory = getBeanFactory();
 if (beanFactory.containsLocalBean(MESSAGE_SOURCE_BEAN_NAME)) {
 this.messageSource = beanFactory.getBean(MESSAGE_SOURCE_BEAN_NAME,MessageSource.class);
 // Make MessageSource aware of parent MessageSource.
 //如果已經註冊了 messageSource && messageSource是HierarchicalMessageSource && messageSource沒有parent && 此IOC有parent 
 if (this.parent != null && this.messageSource instanceof HierarchicalMessageSource) {
 HierarchicalMessageSource hms = (HierarchicalMessageSource) this.messageSource;
 if (hms.getParentMessageSource() == null) {
 // Only set parent context as parent MessageSource if no parent MessageSource
 // registered already.
 hms.setParentMessageSource(getInternalParentMessageSource());
 }
 }
 if (logger.isDebugEnabled()) {
 logger.debug("Using MessageSource [" + this.messageSource + "]");
 }
 }
 //如果沒有註冊messageSource,就建立一個DelegatingMessageSource,並註冊到IOC中
 else {
 // Use empty MessageSource to be able to accept getMessage calls.
 DelegatingMessageSource dms = new DelegatingMessageSource();
 dms.setParentMessageSource(getInternalParentMessageSource());
 this.messageSource = dms;
 beanFactory.registerSingleton(MESSAGE_SOURCE_BEAN_NAME,this.messageSource);
 if (logger.isDebugEnabled()) {
 logger.debug("Unable to locate MessageSource with name '" + MESSAGE_SOURCE_BEAN_NAME +
  "': using default [" + this.messageSource + "]");
 }
 }
}

8.initApplicationEventMulticaster

protected void initApplicationEventMulticaster() {
 ConfigurableListableBeanFactory beanFactory = getBeanFactory();
 //如果有開發自定的applicationEventMulticaster例項bean,則設定IOC的事件廣播器為該例項
 if (beanFactory.containsLocalBean(APPLICATION_EVENT_MULTICASTER_BEAN_NAME)) {
 this.applicationEventMulticaster =
 beanFactory.getBean(APPLICATION_EVENT_MULTICASTER_BEAN_NAME,ApplicationEventMulticaster.class);
 if (logger.isDebugEnabled()) {
 logger.debug("Using ApplicationEventMulticaster [" + this.applicationEventMulticaster + "]");
 }
 }
 //如果沒有applicationEventMulticaster,就設定一個SimpleApplicationEventMulticaster
 else {
 this.applicationEventMulticaster = new SimpleApplicationEventMulticaster(beanFactory);
 beanFactory.registerSingleton(APPLICATION_EVENT_MULTICASTER_BEAN_NAME,this.applicationEventMulticaster);
 if (logger.isDebugEnabled()) {
 logger.debug("Unable to locate ApplicationEventMulticaster with name '" +
  APPLICATION_EVENT_MULTICASTER_BEAN_NAME +
  "': using default [" + this.applicationEventMulticaster + "]");
 }
 }
}

9.onRefresh

模板設計模式;該方法屬於鉤子方法;子類重寫該方法並在容器重新整理的時候自定義邏輯;

protected void onRefresh() throws BeansException {
		// For subclasses: do nothing by default.
}

10.registerListeners

註冊監聽器分為兩部分:

  1. 向事件分發器註冊硬編碼設定的applicationListener
  2. 向事件分發器註冊一個IOC中的事件監聽器(並不例項化)
protected void registerListeners() {
 // 查出所有通過addApplicationListener方法新增的ApplicationListener,然後註冊到事件廣播器上
 for (ApplicationListener<?> listener : getApplicationListeners()) {
 getApplicationEventMulticaster().addApplicationListener(listener);
 }

 // 查出ioc容器中的所有ApplicationListener,只把他們註冊到事件分發器的ApplicationListenerBean上,
 // 待使用時再進行例項化
 String[] listenerBeanNames = getBeanNamesForType(ApplicationListener.class,false);
 for (String listenerBeanName : listenerBeanNames) {
 getApplicationEventMulticaster().addApplicationListenerBean(listenerBeanName);
 }
}

11.finishBeanFactoryInitialization

finishBeanFactoryInitialization主要是負責初始化單例項的bean;該方法是重點方法,bean的生命週期基本呼叫getBean()方法完成。

protected void finishBeanFactoryInitialization(ConfigurableListableBeanFactory beanFactory) {
 //如果IOC中有conversionService的話,就例項化並設定到IOC中
 //conversionService用於型別轉換
 if (beanFactory.containsBean(CONVERSION_SERVICE_BEAN_NAME) &&
 beanFactory.isTypeMatch(CONVERSION_SERVICE_BEAN_NAME,ConversionService.class)) {
 beanFactory.setConversionService(
 beanFactory.getBean(CONVERSION_SERVICE_BEAN_NAME,ConversionService.class));
 }
 // 如果有LoadTimeWeaverAware,就例項化
 String[] weaverAwareNames = beanFactory.getBeanNamesForType(LoadTimeWeaverAware.class,false,false);
 for (String weaverAwareName : weaverAwareNames) {
 getBean(weaverAwareName);
 }
 // 清理臨時的classLoader
 beanFactory.setTempClassLoader(null);
 // 快取所有beanDefinition的name,以備不時之需
 beanFactory.freezeConfiguration();
 // 例項化所有非non-lazy-init的單例
 beanFactory.preInstantiateSingletons();
}

12.finishRefresh

完成bean建立和初始化過程,通知生命週期處理器 lifecycleProcessor 重新整理過程,同時發出 ContextRefreshEvent 通知。

protected void finishRefresh() {
 // 例項化或初始化lifecycleProcessor
 initLifecycleProcessor();
 // 呼叫lifecycleProcessor的重新整理方法
 getLifecycleProcessor().onRefresh();
 //釋出一個ContextRefreshedEvent事件
 publishEvent(new ContextRefreshedEvent(this));
 // 註冊MBean,用於JMX管理
 LiveBeansView.registerApplicationContext(this);
}

參考資料:

  • 解讀Spring容器的refresh()
  • Spring 原始碼深度解析
  • Spring IoC之ApplicationContext中refresh過程

總結

到此這篇關於Spring教程之refresh()執行邏輯的文章就介紹到這了,更多相關Spring refresh()執行邏輯內容請搜尋我們以前的文章或繼續瀏覽下面的相關文章希望大家以後多多支援我們!