Spring解析Xml註冊Bean流程

来源:https://www.cnblogs.com/sdayup/archive/2020/07/04/13236726.html
-Advertisement-
Play Games

有道無術,術可求; 有術無道,止於術; 讀源碼是一個很枯燥的過程,但是Spring源碼裡面有很多值得學習的地方 加油~!!!!! 前言 使用SpringMVC的時候,通常使用下麵這行代碼來載入Spring的配置文件 ApplicationContext application = new Class ...


有道無術,術可求;

有術無道,止於術;

讀源碼是一個很枯燥的過程,但是Spring源碼裡面有很多值得學習的地方

加油~!!!!!

前言

使用SpringMVC的時候,通常使用下麵這行代碼來載入Spring的配置文件

ApplicationContext application = new ClassPathXmlApplicationContext("webmvc.xml"),那麼這行代碼到底進行了怎麼的操作,接下來就一探究境,看看是如何載入配置文件的

Spring的配置文件

這個配置文件對於已經學會使用SpringMVC的你來說已經再熟悉不過了

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd">
    <bean id="study" class="com.xiaobai.Student">
    </bean>
</beans>

那麼Spring是如何進行Bean的註冊的呢?經過這幾天的源碼查看我寫下了這篇文章來作為筆記,

因為我剛開始看Spring的源碼,裡面有些內容可能理解的不是很到位,有錯誤請指出

源碼查看

再此之前我先bb幾句,為了方便查看源碼,可以去GitHub上下載Spring的源碼導入到Idea或者是eclipse中這樣查看起來更方便些,同時還可以在上面寫一些註釋

既然使用的是ClassPathXmlApplicationContext("webmvc.xml")那就找到這個類的單參構造器查看跟蹤下源碼

/**
	 * Create a new ClassPathXmlApplicationContext, loading the definitions
	 * from the given XML file and automatically refreshing the context.
	 * @param configLocation resource location
	 * @throws BeansException if context creation failed
	 * 這個是創建 了 一個 ClassPathXmlApplicationContext,用來從給的XMl文件中載入規定
	 */
	public ClassPathXmlApplicationContext(String configLocation) throws BeansException {
		this(new String[] {configLocation}, true, null);
	}

這裡調用的是本類中的另外一個三個參數的構造方法,便進入到了下麵這些代碼中

/**
	 * Create a new ClassPathXmlApplicationContext with the given parent,
	 * loading the definitions from the given XML files.
	 * @param configLocations array of resource locations
	 * @param refresh whether to automatically refresh the context,
	 * loading all bean definitions and creating all singletons.
	 * Alternatively, call refresh manually after further configuring the context.
	 * @param parent the parent context
	 * @throws BeansException if context creation failed
	 * @see #refresh()
	 */
	public ClassPathXmlApplicationContext(
			String[] configLocations, boolean refresh, @Nullable ApplicationContext parent)
			throws BeansException {

		super(parent);
    	//設置配置文件的路徑
		setConfigLocations(configLocations);
		if (refresh) {
      	   //重要的方法,需要進入查看
			refresh();
		}
	}

這裡來說下這個方法的參數的意思:

  • configLocations:這個裡面保存的是配置文件的路徑
  • Refresh:是否自動刷新上下文
  • parent:父上下文

設置資源載入器

要跟蹤下super(parent)這行代碼,在它的父類中(AbstractApplicationContext類裡面),有下麵的代碼,這段代碼的作 用是獲取一個SpringResource的載入器用來載入資源文件(這裡你可以理解為是為了載入webmvc.xml配置文件做前期的準備)

protected ResourcePatternResolver getResourcePatternResolver() {
	return new PathMatchingResourcePatternResolver(this);
}
//下麵的方法在PathMatchingResourcePatternResolver類中,為了查看方便我將這兩個方法寫在了一起
public PathMatchingResourcePatternResolver(ResourceLoader resourceLoader) {
	Assert.notNull(resourceLoader, "ResourceLoader must not be null");
	this.resourceLoader = resourceLoader;
}

在PathMatchingResourcePatternResolver構造方法中就設置了一個資源載入器

設置Bean信息位置

這個裡面有一個setConfigLocations方法,這個裡面會設置Bean配置信息的位置,這個方法的所在的類是AbstractRefreshableConfigApplicationContext,它和CLassPathXmlApplicationContext之間是繼承的關係

@Nullable
private String[] configLocations;
public void setConfigLocations(@Nullable String... locations) {
		if (locations != null) {
			Assert.noNullElements(locations, "Config locations must not be null");
			this.configLocations = new String[locations.length];
			for (int i = 0; i < locations.length; i++) {
				this.configLocations[i] = resolvePath(locations[i]).trim();
			}
		}
		else {
			this.configLocations = null;
		}
	}

這裡面的configLocations的是一個數組,setConfigLocations方法的參數是一個可變參數,這個方法的作用是將多個路徑放到configLocations數組中

閱讀refresh

這個方法可以說是一個非常重要的一個方法,這在個方法裡面規定了容器的啟動流程,具體的邏輯通過ConfigurableApplicationContext介面的子類實現

@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 {
				//這裡面的代碼我刪除掉了,因為我們本文是看的解析XML創建 Bean的文章,這裡的代碼暫時用不到,我就刪除了,要不然代碼太多了
			}

			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的配置文件是在這個方法裡面的refreshBeanFactory方法來處理的,這個方法是在AbstractRefreshableApplicationContext類中實現的

@Override
protected final void refreshBeanFactory() throws BeansException {
  if (hasBeanFactory()) {
    destroyBeans();
    closeBeanFactory();
  }
  try {
    DefaultListableBeanFactory beanFactory = createBeanFactory();
    beanFactory.setSerializationId(getId());
    customizeBeanFactory(beanFactory);
    //開始解析配置文件
    loadBeanDefinitions(beanFactory);
    synchronized (this.beanFactoryMonitor) {
      this.beanFactory = beanFactory;
    }
  }
  catch (IOException ex) {
    throw new ApplicationContextException("I/O error parsing bean definition source for " + getDisplayName(), ex);
  }
}

這裡有一個方法是loadBeanDefinitions(beanFactory)在這個方法裡面就開始解析配置文件了,進入這個方法

@Override
protected void loadBeanDefinitions(DefaultListableBeanFactory beanFactory) throws BeansException, IOException {
  // Create a new XmlBeanDefinitionReader for the given BeanFactory.
  XmlBeanDefinitionReader beanDefinitionReader = new XmlBeanDefinitionReader(beanFactory);

  // Configure the bean definition reader with this context's
  // resource loading environment.
  beanDefinitionReader.setEnvironment(this.getEnvironment());
  beanDefinitionReader.setResourceLoader(this);
  beanDefinitionReader.setEntityResolver(new ResourceEntityResolver(this));

  // Allow a subclass to provide custom initialization of the reader,
  // then proceed with actually loading the bean definitions.
  initBeanDefinitionReader(beanDefinitionReader);
  //Bean讀取器實現載入的方法
  loadBeanDefinitions(beanDefinitionReader);
}

進入到loadBeanDefinitions(XmlBeanDefinitionReader reader)方法

XML Bean讀取器載入Bean配置資源

protected void loadBeanDefinitions(XmlBeanDefinitionReader reader) throws BeansException, IOException {
 //獲娶Bean配置資源的位置
  Resource[] configResources = getConfigResources();
  if (configResources != null) {
    reader.loadBeanDefinitions(configResources);
  }
  String[] configLocations = getConfigLocations();
  if (configLocations != null) {
    reader.loadBeanDefinitions(configLocations);
  }
}

但是本文的教程是通過ClassPathXmlApplicationContext來舉的例子,getConfigResources()方法返回的是空的,就執行下麵的分支

說點和本文有關也有可能沒有關係的話

當代碼看到這裡,學習過設計模式的同鞋可能會發現我們看過的這些代碼里也涉及到了委派模式策略模式因為Spring框架中使用到了很多的設計模式,所以說在看一些框架源碼的時候,我們儘可能的先學習下設計模式,不管是對於看源碼來說或者是對於在公司中工作都是啟到了很重要的作用,在工作中使用了設計模式對於以後系統的擴展或者是維護來說都是比較方便的。當然學習設計模式也是沒有那麼的簡單,或許你看了關於設計模式的視頻或者是一些書籍,但是在工作中如果是想很好的運用出來,還是要寫很多的代碼和常用設計模式的。

學習設計模式也是投入精力的,Scott Mayer在《Effective C++》也說過:C++新手和老手的區別就是前者手背上有很多的傷疤。

未完....


您的分享是我們最大的動力!

-Advertisement-
Play Games
更多相關文章
  • from docx import Document w=Document(r'F:\word練習\表格.docx') #刪除表 print(len(w.tables)) t=w.tables[0] t._element.getparent().remove(t._element) print(len ...
  • from docx import Document w=Document(r'F:\word練習\表格.docx') table_1=w.tables[0] #刪除行 print(len(table_1.rows)) row2=table_1.rows[1] row2._element.getpar ...
  • 值傳遞和引用傳遞: 值傳遞和引用傳遞的區別並不是傳遞的內容。而是實參到底有沒有被覆制一份給形參。在判斷實參內容有沒有受影響的時候,要看傳的的是什麼,如果你傳遞的是個地址,那麼就看這個地址的變化會不會有影響,而不是看地址指向的對象的變化。 Java中當傳遞的參數是對象時,其實還是值傳遞的,只不過對於對 ...
  • pygame 的聲音播放 1. sound 對象 在初始化聲音設備後就可以讀取一個音樂文件到一個 Sound 對象中。pygame.mixer.sound() 接收一個文件名,也可以是一個文件對象,不過這個文件對象必須是 WAV 或者 OGG 文件。 hello_sound = pygame.mix ...
  • 在使用dubbo時,通常會遇到timeout這個屬性,timeout屬性的作用是:給某個服務調用設置超時時間,如果服務在設置的時間內未返回結果,則會拋出調用超時異常:TimeoutException,在使用的過程中,我們有時會對provider和consumer兩個配置都會設置timeout值,那麼 ...
  • JAVA線程虛假喚醒 線程虛假喚醒問題描述 ​ 在JDK API文檔中,關於Object類的wait()方法有這樣一句話描述"線程也可以喚醒,而不會被通知,中斷或超時,即所謂的虛假喚醒 。 雖然這在實踐中很少會發生,但應用程式必須通過測試應該使線程被喚醒的條件來防範,並且如果條件不滿足則繼續等待", ...
  • 原文地址:https://www.wjcms.net/archives/vue%E5%AE%89%E8%A3%85%E5%8F%8A%E5%88%9B%E5%BB%BA%E9%A1%B9%E7%9B%AE%E7%9A%84%E5%87%A0%E7%A7%8D%E6%96%B9%E5%BC%8F VU ...
  • 原文地址:https://www.wjcms.net/archives/node%E6%9B%B4%E6%96%B0%E6%8A%A5%E9%94%99checkpermissionsmissingwriteaccesstousrlibnodemodulesn node更新報錯:checkPermi ...
一周排行
    -Advertisement-
    Play Games
  • 前言 在我們開發過程中基本上不可或缺的用到一些敏感機密數據,比如SQL伺服器的連接串或者是OAuth2的Secret等,這些敏感數據在代碼中是不太安全的,我們不應該在源代碼中存儲密碼和其他的敏感數據,一種推薦的方式是通過Asp.Net Core的機密管理器。 機密管理器 在 ASP.NET Core ...
  • 新改進提供的Taurus Rpc 功能,可以簡化微服務間的調用,同時可以不用再手動輸出模塊名稱,或調用路徑,包括負載均衡,這一切,由框架實現並提供了。新的Taurus Rpc 功能,將使得服務間的調用,更加輕鬆、簡約、高效。 ...
  • 順序棧的介面程式 目錄順序棧的介面程式頭文件創建順序棧入棧出棧利用棧將10進位轉16進位數驗證 頭文件 #include <stdio.h> #include <stdbool.h> #include <stdlib.h> 創建順序棧 // 指的是順序棧中的元素的數據類型,用戶可以根據需要進行修改 ...
  • 前言 整理這個官方翻譯的系列,原因是網上大部分的 tomcat 版本比較舊,此版本為 v11 最新的版本。 開源項目 從零手寫實現 tomcat minicat 別稱【嗅虎】心有猛虎,輕嗅薔薇。 系列文章 web server apache tomcat11-01-官方文檔入門介紹 web serv ...
  • C總結與剖析:關鍵字篇 -- <<C語言深度解剖>> 目錄C總結與剖析:關鍵字篇 -- <<C語言深度解剖>>程式的本質:二進位文件變數1.變數:記憶體上的某個位置開闢的空間2.變數的初始化3.為什麼要有變數4.局部變數與全局變數5.變數的大小由類型決定6.任何一個變數,記憶體賦值都是從低地址開始往高地 ...
  • 如果讓你來做一個有狀態流式應用的故障恢復,你會如何來做呢? 單機和多機會遇到什麼不同的問題? Flink Checkpoint 是做什麼用的?原理是什麼? ...
  • C++ 多級繼承 多級繼承是一種面向對象編程(OOP)特性,允許一個類從多個基類繼承屬性和方法。它使代碼更易於組織和維護,並促進代碼重用。 多級繼承的語法 在 C++ 中,使用 : 符號來指定繼承關係。多級繼承的語法如下: class DerivedClass : public BaseClass1 ...
  • 前言 什麼是SpringCloud? Spring Cloud 是一系列框架的有序集合,它利用 Spring Boot 的開發便利性簡化了分散式系統的開發,比如服務註冊、服務發現、網關、路由、鏈路追蹤等。Spring Cloud 並不是重覆造輪子,而是將市面上開發得比較好的模塊集成進去,進行封裝,從 ...
  • class_template 類模板和函數模板的定義和使用類似,我們已經進行了介紹。有時,有兩個或多個類,其功能是相同的,僅僅是數據類型不同。類模板用於實現類所需數據的類型參數化 template<class NameType, class AgeType> class Person { publi ...
  • 目錄system v IPC簡介共用記憶體需要用到的函數介面shmget函數--獲取對象IDshmat函數--獲得映射空間shmctl函數--釋放資源共用記憶體實現思路註意 system v IPC簡介 消息隊列、共用記憶體和信號量統稱為system v IPC(進程間通信機制),V是羅馬數字5,是UNI ...