欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

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

 更新時間:2020年09月01日 10:55:48   作者:溪~源  
這篇文章主要給大家介紹了關于Spring教程之refresh()執(zhí)行邏輯的相關資料,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧

前言

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

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

概覽

refresh

該方法是 Spring Bean 加載的核心,它是 ClassPathXmlApplicationContext 的父類 AbstractApplicationContext 的一個方法 , 顧名思義,用于刷新整個Spring 上下文信息,定義了整個 Spring 上下文加載的流程。
先看下refresh()方法總體:

@Override
public void refresh() throws BeansException, IllegalStateException {
 synchronized (this.startupShutdownMonitor) {
 // 準備預處理:記錄容器的啟動時間startupDate, 標記容器為激活,初始化上下文環(huán)境如文件路徑信息,驗證必填屬性是否填寫 
 this.prepareRefresh();
 // **告訴子類去刷新bean工廠,此方法解析配置文件并將bean信息存儲到beanDefinition中,注冊到BeanFactory(但是未被初始化,僅將信息寫到了beanDefination的map中)**重點方法,下面的操作都基于這個beanFactory進行的
 ConfigurableListableBeanFactory beanFactory = this.obtainFreshBeanFactory();
 // 設置beanFactory的基本屬性:類加載器,添加多個beanPostProcesser
 this.prepareBeanFactory(beanFactory);
 try {
 // 空實現(xiàn):允許子類上下文中對beanFactory做后期處理
 this.postProcessBeanFactory(beanFactory);
 /**************************以上是BeanFactory的創(chuàng)建及預準備工作 ****************/
 // 調(diào)用BeanFactoryPostProcessor各個實現(xiàn)類的方法
 this.invokeBeanFactoryPostProcessors(beanFactory);
 // 注冊 BeanPostProcessor 的實現(xiàn)類,注意看和 BeanFactoryPostProcessor 的區(qū)別
 // 此接口兩個方法: postProcessBeforeInitialization 和 postProcessAfterInitialization
 // 兩個方法分別在 Bean 初始化之前和初始化之后得到執(zhí)行。注意,到這里 Bean 還沒初始化
 this.registerBeanPostProcessors(beanFactory);
 //初始化ApplicationContext的MessageSource組件(資源文件),如國際化文件,消息解析,綁定等
 this.initMessageSource();
 //初始化ApplicationContext事件廣播器
 this.initApplicationEventMulticaster();
 // 初始化子類特殊bean(鉤子方法)
 this.onRefresh();
 // 獲取所有的事件監(jiān)聽器,并將監(jiān)聽器注冊到事件廣播器
 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;
			}
		}

明細

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

1.prepareRefresh

準備預處理:記錄spring容器的啟動時間startupDate, 標記容器為激活,初始化上下文環(huán)境如文件路徑信息,驗證必填屬性是否填寫。

  • 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(); //創(chuàng)建了一個this.beanFactory = new DefaultListableBeanFactory();設置了序列化的ID
 //返回剛才創(chuàng)建的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,用于向實現(xiàn)類ApplitionContextAware中,調(diào)用setApplicationContext方法,并將ApplicationContext作為參數(shù)。
 	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,如果有l(wèi)oadTimeWeaver的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的能力,就可以執(zhí)行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 ,
 //就先執(zhí)行它的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);
 
 //先調(diào)用registryPostProcessorBeans中的所有postProcessBeanDefinitionRegistry方法
 for (BeanDefinitionRegistryPostProcessor postProcessor : registryPostProcessorBeans) {
 postProcessor.postProcessBeanDefinitionRegistry(registry);
 }
 //先調(diào)用 registryPostProcessors中的postProcessBeanFactory方法
 //再調(diào)用 registryPostProcessorBeans中的postProcessBeanFactory方法
 //最后調(diào)用 regularPostProcessors中的postProcessBeanFactory方法
 invokeBeanFactoryPostProcessors(registryPostProcessors, beanFactory);
 invokeBeanFactoryPostProcessors(registryPostProcessorBeans, beanFactory);
 invokeBeanFactoryPostProcessors(regularPostProcessors, beanFactory);
 
 //對于IOC容器中注冊的BeanDefinitionRegistryPostProcessor來說,還要放置到processedBeans中,放置重復調(diào)用
 processedBeans.addAll(beanMap.keySet());
 }
 else {
 //如果IOC就是一個普通的BeanFacotry,就直接從context中取出所有的BeanFactoryPostProcessor,并調(diào)用他們的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, true, false);

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

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

 // 最后執(zhí)行普通的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, true, false);

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

 //按照排序接口分類。
 //這里需要注意的是,priorityOrderedPostProcessors里面裝的是BeanPostProcessor
 //而orderedPostProcessorNames和nonOrderedPostProcessorNames里面裝的是BeanPostProcessor的name
 //原因是:實例化BeanPostProcessor實現(xiàn)類的時候,也需要調(diào)用IOC中已有的BeanPostProcessor,所以Spring這里沒有提前實例化Orderd接口和普通的BeanPostProcessor。
 //因此,這里有一個有趣的現(xiàn)象,示例化Orderd接口的BeanProcessor的時候,會使用PriorityOrdered的BeanPostProcessor進行處理
 //實例化普通的BeanProcessor時,會先后經(jīng)過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) {
 //這里才進行實例化,所以會使用實現(xiàn)了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) {
 //這里才進行實例化,所以會使用實現(xiàn)了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,如果沒有自己創(chuàng)建一個DelegatingMessageSource;
    MessageSource:取出國際化配置文件中的某個key的值;能按照區(qū)域信息獲?。?/li>
  • 將創(chuàng)建完成的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.
 //如果已經(jīng)注冊了 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,就創(chuàng)建一個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();
 //如果有開發(fā)自定的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

注冊監(jiān)聽器分為兩部分:

  1. 向事件分發(fā)器注冊硬編碼設置的applicationListener
  2. 向事件分發(fā)器注冊一個IOC中的事件監(jiān)聽器(并不實例化)
protected void registerListeners() {
 // 查出所有通過addApplicationListener方法添加的ApplicationListener,然后注冊到事件廣播器上
 for (ApplicationListener<?> listener : getApplicationListeners()) {
 getApplicationEventMulticaster().addApplicationListener(listener);
 }

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

11.finishBeanFactoryInitialization

finishBeanFactoryInitialization主要是負責初始化單實例的bean;該方法是重點方法,bean的生命周期基本調(diào)用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創(chuàng)建和初始化過程,通知生命周期處理器 lifecycleProcessor 刷新過程,同時發(fā)出 ContextRefreshEvent 通知。

protected void finishRefresh() {
 // 實例化或初始化lifecycleProcessor
 initLifecycleProcessor();
 // 調(diào)用lifecycleProcessor的刷新方法
 getLifecycleProcessor().onRefresh();
 //發(fā)布一個ContextRefreshedEvent事件
 publishEvent(new ContextRefreshedEvent(this));
 // 注冊MBean,用于JMX管理
 LiveBeansView.registerApplicationContext(this);
}

參考資料:

總結

到此這篇關于Spring教程之refresh()執(zhí)行邏輯的文章就介紹到這了,更多相關Spring refresh()執(zhí)行邏輯內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!

相關文章

  • Java如何在PPT中繪制圖形

    Java如何在PPT中繪制圖形

    這篇文章主要介紹了Java如何在PPT中繪制圖形,Microsoft PowerPoint可支持在幻燈片中插入各種類型的圖形并且可設置圖形填充、線條顏色、圖形大小、位置等。下面將通過Java編程來演示在PPT中繪制圖形的方法,需要的朋友可以參考下
    2019-07-07
  • Java中冒泡排序的原生實現(xiàn)方法(正序與逆序)

    Java中冒泡排序的原生實現(xiàn)方法(正序與逆序)

    這篇文章主要給大家介紹了關于Java中冒泡排序的原生實現(xiàn)方法(正序與逆序)的相關資料,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧
    2020-11-11
  • java中參數(shù)傳遞方式詳解

    java中參數(shù)傳遞方式詳解

    這篇文章主要介紹了java中參數(shù)傳遞方式詳解的相關資料,需要的朋友可以參考下
    2017-03-03
  • 解決static類使用@Value獲取yml文件獲取不到的問題

    解決static類使用@Value獲取yml文件獲取不到的問題

    在靜態(tài)類中直接使用@Value注解無法獲取yml文件中的配置,解決方案是在工具類Utils中創(chuàng)建靜態(tài)的setter方法,并從外部類ServiceClass中調(diào)用這個方法來設置值,這種方法通過外部調(diào)用來間接設置靜態(tài)變量的值,從而成功讀取yml配置
    2024-09-09
  • java多線程編程學習(線程間通信)

    java多線程編程學習(線程間通信)

    下面小編就為大家?guī)硪黄猨ava多線程編程學習(線程間通信)。小編覺得挺不錯的,現(xiàn)在就分享給大家,也給大家做個參考。一起跟隨小編過來看看吧
    2017-09-09
  • maven項目在實踐中的構建管理之路的方法

    maven項目在實踐中的構建管理之路的方法

    這篇文章主要介紹了maven項目在實踐中的構建管理之路的方法,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧
    2019-05-05
  • spring的@Transactional注解用法解讀

    spring的@Transactional注解用法解讀

    這篇文章主要介紹了spring的@Transactional注解用法解讀,具有一定借鑒價值,需要的朋友可以參考下
    2018-01-01
  • SpringBoot+netty-socketio實現(xiàn)服務器端消息推送

    SpringBoot+netty-socketio實現(xiàn)服務器端消息推送

    這篇文章主要介紹了SpringBoot+netty-socketio實現(xiàn)服務器端消息推送,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧
    2021-03-03
  • java調(diào)用webService接口的代碼實現(xiàn)

    java調(diào)用webService接口的代碼實現(xiàn)

    本文主要介紹了java調(diào)用webService接口的代碼實現(xiàn),文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧
    2023-02-02
  • Java主流壓縮解壓工具對比、用法與選取詳解

    Java主流壓縮解壓工具對比、用法與選取詳解

    開發(fā)過程中可能會用到壓縮文件的需求,下面這篇文章主要給大家介紹了關于Java主流壓縮解壓工具對比、用法與選取的相關資料,文中通過代碼介紹的非常詳細,需要的朋友可以參考下
    2024-01-01

最新評論