源碼分析 | 像盜墓同樣分析Spring是怎麼初始化xml並註冊bean的

微信公衆號:bugstack蟲洞棧 | 博客:bugstack.cn
沉澱、分享、成長,專一於原創專題案例,以最易學習編程的方式分享知識,讓本身和他人都能有所收穫。目前已完成的專題有;Netty4.x實戰專題案例、用Java實現JVM、基於JavaAgent的全鏈路監控、手寫RPC框架、架構設計專題案例[Ing]等。
你用劍🗡、我用刀🔪,好的代碼都很燒😏,望你不吝出招💨!java

1、前言介紹

每每簡單的背後都有人爲你承擔着不簡單,Spring 就是這樣的傢伙!而分析它的源碼就像鬼吹燈,須要尋龍、點穴、分金、定位,最後每每受點傷(時間)、流點血(精力)、才能得到寶藏(成果)。node

另外鑑於以前分析spring-mybatis、quartz,一篇寫了將近2萬字,內容過於又長又幹,挖藏師好辛苦,看戲的也憋着腎,因此此次分析spring源碼分塊解讀,便於理解、便於消化。spring

那麼,這一篇就從 bean 的加載開始,從 xml 配置文件解析 bean 的定義,到註冊到 Spring 的核心類 DefaultListableBeanFactory ,盜墓過程以下;編程

微信公衆號:bugstack蟲洞棧 & 盜墓

從上圖能夠看到從 xml 解析出 bean 到註冊完成須要經歷過8個核心類以及22個方法跳轉流程,這也是本文後面須要重點分析的內容。好!那麼就當爲了你的錢程一塊兒盜墓吧!微信

2、案例工程

對於源碼分析必定要單獨列一個簡單的工程,一針見血的搞你最須要的地方,模擬、驗證、調試。如今這個案例工程還很簡單,隨着後面分析內容的增長,會不斷的擴充。總體工程能夠下載,能夠關注公衆號:bugstack蟲洞棧 | 回覆:源碼分析mybatis

itstack-demo-code-spring
└── src
    ├── main
    │   ├── java
    │   │   └── org.itstack.demo
    │   │       └── UserService.java   
    │   └── resources	
    │       └── spring-config.xml
    └── test
         └── java
             └── org.itstack.demo.test			
                 └── ApiTest.java
複製代碼

3、環境配置

  1. JDK 1.8
  2. IDEA 2019.3.1
  3. Spring 4.3.24.RELEASE

4、源碼分析

整個 bean 註冊過程核心功能包括;配置文件加載、工廠建立、XML解析、Bean定義、Bean註冊,執行流程以下;架構

微信公衆號:bugstack蟲洞棧 & 盜墓

從上圖的註冊 bean 流程看到,核心類包括;框架

  • ClassPathXmlApplicationContext
  • AbstractXmlApplicationContext
  • AbstractRefreshableApplicationContext
  • AbstractXmlApplicationContext
  • AbstractBeanDefinitionReader
  • XmlBeanDefinitionReader
  • DefaultBeanDefinitionDocumentReader
  • DefaultListableBeanFactory

好!摸金分金定穴完事,搬山的搬山、卸嶺的卸嶺,開始搞!dom

1. 先扔個 helloworld 測試下

UserService.java & 定義一個 bean,Spring 萬物皆可 beanide

public class UserService {

    public String queryUserInfo(Long userId) {
        return "花花 id:" + userId;
    }

}
複製代碼

spring-config.xml & 在 xml 配置 bean 內容

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd"
       default-autowire="byName">

    <bean id="userService" class="org.itstack.demo.UserService" scope="singleton"/>

</beans>
複製代碼

ApiTest.java & 單元測試類

@Test
public void test_XmlBeanFactory() {
    BeanFactory beanFactory = new XmlBeanFactory(new ClassPathResource("spring-config.xml"));
    UserService userService = beanFactory.getBean("userService", UserService.class);
    logger.info("測試結果:{}", userService.queryUserInfo(1000L));
}

@Test
public void test_ClassPathXmlApplicationContext() {
    BeanFactory beanFactory = new ClassPathXmlApplicationContext("spring-config.xml");
    UserService userService = beanFactory.getBean("userService", UserService.class);
    logger.info("測試結果:{}", userService.queryUserInfo(1000L));
}
複製代碼

兩個單測方法均可以作結果輸出,可是 XmlBeanFactory 已經標記爲 @Deprecated 就是告訴咱們這個墓穴啥也沒有了,被盜過了,別看了。好!咱們也不看他了,咱們看如今推薦的2號墓 ClassPathXmlApplicationContext

如上不出意外正確結果以下;

23:34:24.699 [main] INFO  org.itstack.demo.test.ApiTest - 測試結果:花花 id:1000

Process finished with exit code 0
複製代碼

2. 把 xml 解析過程搞定

在整個 bean 的註冊過程當中,xml 解析是很是大的一塊,也是很是重要的一塊。若是順着 bean 工廠初始化分析,那麼一層層扒開,就像陳玉樓墓穴挖到一半,遇到大蜈蚣同樣難纏。因此咱們先把蜈蚣搞定!

@Test
public void test_DocumentLoader() throws Exception {
    
	// 設置資源
    EncodedResource encodedResource = new EncodedResource(new ClassPathResource("spring-config.xml"));
    
	// 加載解析
    InputSource inputSource = new InputSource(encodedResource.getResource().getInputStream());
    DocumentLoader documentLoader = new DefaultDocumentLoader();
    Document doc = documentLoader.loadDocument(inputSource, new ResourceEntityResolver(new PathMatchingResourcePatternResolver()), new DefaultHandler(), 3, false);
    
	// 輸出結果
    Element root = doc.getDocumentElement();
    NodeList nodeList = root.getChildNodes();
    for (int i = 0; i < nodeList.getLength(); i++) {
        Node node = nodeList.item(i);
        if (!(node instanceof Element)) continue;
        Element ele = (Element) node;
        if (!"bean".equals(ele.getNodeName())) continue;
        String id = ele.getAttribute("id");
        String clazz = ele.getAttribute("class");
        String scope = ele.getAttribute("scope");
        logger.info("測試結果 beanName:{} beanClass:{} scope:{}", id, clazz, scope);
    }
	
}
複製代碼

可能初次看這段代碼仍是有點暈的,但這樣提煉出來單獨解決,至少給你一種有抓手的感受。在 spring 解析 xml 時候首先是將配置資源交給 ClassPathResource ,再經過構造函數傳遞給 EncodedResource;

private EncodedResource(Resource resource, String encoding, Charset charset) {
	super();
	Assert.notNull(resource, "Resource must not be null");
	this.resource = resource;
	this.encoding = encoding;
	this.charset = charset;
}
複製代碼

以上這個過程仍是比較簡單的,只是一個初始化過程。接下來是經過 Document 解析處理 xml 文件。這個過程是仿照 spring 建立時候須要的參數信息進行組裝,以下;

documentLoader.loadDocument(inputSource, new ResourceEntityResolver(new PathMatchingResourcePatternResolver()), new DefaultHandler(), 3, false);

public Document loadDocument(InputSource inputSource, EntityResolver entityResolver, ErrorHandler errorHandler, int validationMode, boolean namespaceAware) throws Exception {
	DocumentBuilderFactory factory = createDocumentBuilderFactory(validationMode, namespaceAware);
	if (logger.isDebugEnabled()) {
		logger.debug("Using JAXP provider [" + factory.getClass().getName() + "]");
	}
	DocumentBuilder builder = createDocumentBuilder(factory, entityResolver, errorHandler);
	return builder.parse(inputSource);
}
複製代碼

經過上面的代碼獲取 org.w3c.dom.Document, Document 裏面此時包含了全部 xml 的各個 Node 節點信息,最後輸出節點內容,以下;

Element root = doc.getDocumentElement();
NodeList nodeList = root.getChildNodes();
複製代碼

好!測試一下,正常狀況下,結果以下;

23:47:00.249 [main] INFO  org.itstack.demo.test.ApiTest - 測試結果 beanName:userService beanClass:org.itstack.demo.UserService scope:singleton

Process finished with exit code 0
複製代碼

能夠看到的咱們的 xml 配置內容已經完完整整的取出來了,接下來就交給 spring 進行處理了。紅姑娘、鷓鴣哨、我們出發!

3. ClassPathXmlApplicationContext 構造函數初始化過程

ClassPathXmlApplicationContext.java & 截取部分代碼

public ClassPathXmlApplicationContext(String[] configLocations, boolean refresh, ApplicationContext parent) throws BeansException {
	super(parent);
	setConfigLocations(configLocations);
	if (refresh) {
		refresh();
	}
}
複製代碼
  • 源碼139行: setConfigLocations 設置咱們的配置的資源位置信息
  • 重點在 refresh() 這個方法裏面內容很是多,隨着文章的編寫會陸續分析。

4. AbstractApplicationContext 初始化工廠

AbstractApplicationContext.java & 部分代碼截取

@Override
public void refresh() throws BeansException, IllegalStateException {
	synchronized (this.startupShutdownMonitor) {
		// 設置容器初始化
		prepareRefresh();
		
		// 讓子類進行 BeanFactory 初始化,而且將 Bean 信息 轉換爲 BeanFinition,最後註冊到容器中
		// 注意,此時 Bean 尚未初始化,只是配置信息都提取出來了
		ConfigurableListableBeanFactory beanFactory = obtainFreshBeanFactory();

		...
	}
}
複製代碼
  • 源碼514行: 這一行是咱們重點日後分析的內容,它主要開始處理 xml 中 bean 的初始化過程,但此時不會註冊,意思就是你經過 beanFactory.getBean 還得到不到內容

AbstractApplicationContext.java & 部分代碼截取

protected ConfigurableListableBeanFactory obtainFreshBeanFactory() {
	refreshBeanFactory();
	ConfigurableListableBeanFactory beanFactory = getBeanFactory();
	if (logger.isDebugEnabled()) {
		logger.debug("Bean factory for " + getDisplayName() + ": " + beanFactory);
	}
	return beanFactory;
}
複製代碼
  • 這一層方法在處理完解析後還會返回 bean 工廠
  • 源碼614行: 回到咱們主線繼續分析解析過程,往下一層繼續看

5. AbstractRefreshableApplicationContext 刷新上下文

AbstractRefreshableApplicationContext.java & 部分代碼截取

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);
	}
}
複製代碼
  • 這裏包括判斷對 bean 工廠判斷的以及銷燬和初始化建立
  • 源碼129行: loadBeanDefinitions(beanFactory);,獲取 bean 工廠後繼續咱們 bean 註冊過程

6. AbstractXmlApplicationContext xml配置處理

AbstractXmlApplicationContext.java & 部分代碼截取

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);
	loadBeanDefinitions(beanDefinitionReader);
}
複製代碼
  • 源碼82行: XmlBeanDefinitionReader 定義配置文件讀取類,並設置基礎的屬性信息,getEnvironment、ResourceEntityResolver
  • 源碼93行: loadBeanDefinitions 在拿到 beanDefinitionReader 繼續執行

AbstractXmlApplicationContext.java & 部分代碼截取

protected void loadBeanDefinitions(XmlBeanDefinitionReader reader) throws BeansException, IOException {
	Resource[] configResources = getConfigResources();
	if (configResources != null) {
		reader.loadBeanDefinitions(configResources);
	}
	String[] configLocations = getConfigLocations();
	if (configLocations != null) {
		reader.loadBeanDefinitions(configLocations);
	}
}
複製代碼
  • 源碼121行: 獲取咱們最開始設置的資源信息,在這裏也就是 spring-config.xml
  • 源碼127行: 經過 beanDefinitionReader 開始加載解析配置文件

7. AbstractBeanDefinitionReader 配置文件加載

AbstractBeanDefinitionReader.java & 部分代碼截取

public int loadBeanDefinitions(String... locations) throws BeanDefinitionStoreException {
	Assert.notNull(locations, "Location array must not be null");
	int counter = 0;
	for (String location : locations) {
		counter += loadBeanDefinitions(location);
	}
	return counter;
}
複製代碼
  • 抽象類是中提供了加載解析的方法,每解析一組就計數一次
  • 源碼252行: loadBeanDefinitions(location) 循環加載 bean 的定義進行解析

AbstractBeanDefinitionReader.java & 部分代碼截取

public int loadBeanDefinitions(String location) throws BeanDefinitionStoreException {
	return loadBeanDefinitions(location, null);
}
複製代碼
  • 類內部提供的單個解析方法,沒有什麼特別。繼續往下

AbstractBeanDefinitionReader.java & 部分代碼截取

public int loadBeanDefinitions(String location, Set<Resource> actualResources) throws BeanDefinitionStoreException {
	ResourceLoader resourceLoader = getResourceLoader();
	if (resourceLoader == null) {
		throw new BeanDefinitionStoreException(
				"Cannot import bean definitions from location [" + location + "]: no ResourceLoader available");
	}
	
	if (resourceLoader instanceof ResourcePatternResolver) {
		// Resource pattern matching available.
		try {
			Resource[] resources = ((ResourcePatternResolver) resourceLoader).getResources(location);
			int loadCount = loadBeanDefinitions(resources);
			if (actualResources != null) {
				for (Resource resource : resources) {
					actualResources.add(resource);
				}
			}
			if (logger.isDebugEnabled()) {
				logger.debug("Loaded " + loadCount + " bean definitions from location pattern [" + location + "]");
			}
			return loadCount;
		}
		catch (IOException ex) {
			throw new BeanDefinitionStoreException(
					"Could not resolve bean definition resource pattern [" + location + "]", ex);
		}
	}
	else {
		// Can only load single resources by absolute URL.
		Resource resource = resourceLoader.getResource(location);
		int loadCount = loadBeanDefinitions(resource);
		if (actualResources != null) {
			actualResources.add(resource);
		}
		if (logger.isDebugEnabled()) {
			logger.debug("Loaded " + loadCount + " bean definitions from location [" + location + "]");
		}
		return loadCount;
	}
}
複製代碼
  • 源碼217行: 獲取資源解析,最終執行到 loadBeanDefinitions(resources);,繼續往下

8. XmlBeanDefinitionReader 配置解析

XmlBeanDefinitionReader.java & 部分代碼截取

public int loadBeanDefinitions(EncodedResource encodedResource) throws BeanDefinitionStoreException {
	
	// 判斷驗證
	...
	
	try {
		InputStream inputStream = encodedResource.getResource().getInputStream();
		try {
			InputSource inputSource = new InputSource(inputStream);
			if (encodedResource.getEncoding() != null) {
				inputSource.setEncoding(encodedResource.getEncoding());
			}
			return doLoadBeanDefinitions(inputSource, encodedResource.getResource());
		}
		finally {
			inputStream.close();
		}
	}
	catch (IOException ex) {
		throw new BeanDefinitionStoreException(
				"IOException parsing XML document from " + encodedResource.getResource(), ex);
	}
	finally {
		currentResources.remove(encodedResource);
		if (currentResources.isEmpty()) {
			this.resourcesCurrentlyBeingLoaded.remove();
		}
	}
}
複製代碼
  • 源碼330行 -> 336行: 這個就是 xml 的解析過程,在咱們最開始優先分析的部分,這一部分真正的要爲解析 xml 作準備

9. XmlBeanDefinitionReader 配置文件讀取

XmlBeanDefinitionReader.java & 部分代碼截取

protected int doLoadBeanDefinitions(InputSource inputSource, Resource resource) throws BeanDefinitionStoreException {
	try {
		Document doc = doLoadDocument(inputSource, resource);
		return registerBeanDefinitions(doc, resource);
	} catch(){}
	
}
複製代碼
  • 源碼391行: 此時就獲取到了 Document ,這裏面就包括了全部的節點信息,也就是咱們的 bean 的定義
  • 源碼392行: 經過 doc 與 資源信息開始定義 bean 等待註冊,這個註冊 bean 的過程是須要先定義 bean 的內容,每個 bean 都須要用 BeanDefinitionHolder 封裝

10. DefaultBeanDefinitionDocumentReader 定義bean類

DefaultBeanDefinitionDocumentReader.java & 部分代碼截取

public void registerBeanDefinitions(Document doc, XmlReaderContext readerContext) {
	this.readerContext = readerContext;
	logger.debug("Loading bean definitions");
	Element root = doc.getDocumentElement();
	doRegisterBeanDefinitions(root);
}
複製代碼
  • 源碼93行: 愈來愈熟悉了吧,開始獲取節點元素了,也就能夠獲取 bean 信息

DefaultBeanDefinitionDocumentReader.java & 部分代碼截取

protected void parseBeanDefinitions(Element root, BeanDefinitionParserDelegate deleg if (delegate.isDefaultNamespace(root)) {
		NodeList nl = root.getChildNodes();
		for (int i = 0; i < nl.getLength(); i++) {
			Node node = nl.item(i);
			if (node instanceof Element) {
				Element ele = (Element) node;
				if (delegate.isDefaultNamespace(ele)) {
					parseDefaultElement(ele, delegate);
				}
				else {
					delegate.parseCustomElement(ele);
				}
			}
		}
	}
	else {
		delegate.parseCustomElement(root);
	}
}
複製代碼
  • NodeList 循環處理節點內容,開啓註冊
  • 源碼169行: parseDefaultElement(ele, delegate); 解析元素操做

DefaultBeanDefinitionDocumentReader.java & 部分代碼截取

private void parseDefaultElement(Element ele, BeanDefinitionParserDelegate delegate) {
	if (delegate.nodeNameEquals(ele, IMPORT_ELEMENT)) {
		importBeanDefinitionResource(ele);
	}
	else if (delegate.nodeNameEquals(ele, ALIAS_ELEMENT)) {
		processAliasRegistration(ele);
	}
	else if (delegate.nodeNameEquals(ele, BEAN_ELEMENT)) {
		processBeanDefinition(ele, delegate);
	}
	else if (delegate.nodeNameEquals(ele, NESTED_BEANS_ELEMENT)) {
		// recurse
		doRegisterBeanDefinitions(ele);
	}
}
複製代碼
  • 這個方法會根據不一樣的節點類型;IMPORT_ELEMENT、ALIAS_ELEMENT、BEAN_ELEMENT、NESTED_BEANS_ELEMENT,進行不一樣的操做
  • 源碼190行: 這裏咱們只須要關注 processBeanDefinition(ele, delegate) 便可,處理 bean 操做

DefaultBeanDefinitionDocumentReader.java & 部分代碼截取

protected void processBeanDefinition(Element ele, BeanDefinitionParserDelegate delegate) {
	BeanDefinitionHolder bdHolder = delegate.parseBeanDefinitionElement(ele);
	if (bdHolder != null) {
		bdHolder = delegate.decorateBeanDefinitionIfRequired(ele, bdHolder);
		try {
			// Register the final decorated instance.
			BeanDefinitionReaderUtils.registerBeanDefinition(bdHolder, getReaderContext().getRegistry());
		}
		catch (BeanDefinitionStoreException ex) {
			getReaderContext().error("Failed to register bean definition with name '" +
					bdHolder.getBeanName() + "'", ele, ex);
		}
		// Send registration event.
		getReaderContext().fireComponentRegistered(new BeanComponentDefinition(bdHolder));
	}
}
複製代碼
  • 若是你認真的讀文章了,BeanDefinitionHolder 咱們在上面已經說過一次,這是每個 bean 都會定義的操做,最後交給註冊中心
  • 源碼304行: BeanDefinitionReaderUtils.registerBeanDefinition,類裏的一個靜態註冊操做方法

11. BeanDefinitionReaderUtils bean註冊工具類

BeanDefinitionReaderUtils.java & 部分代碼截取

public static void registerBeanDefinition( BeanDefinitionHolder definitionHolder, BeanDefinitionRegistry registry) throws BeanDefinitionStoreException {
	
	// Register bean definition under primary name.
	String beanName = definitionHolder.getBeanName();
	registry.registerBeanDefinition(beanName, definitionHolder.getBeanDefinition());
	
	// Register aliases for bean name, if any.
	String[] aliases = definitionHolder.getAliases();
	if (aliases != null) {
		for (String alias : aliases) {
			registry.registerAlias(beanName, alias);
		}
	}
}
複製代碼
  • 源碼149行: 將 beanName、BeanDefinition,一同交給最後的註冊中心,最後這個就是 DefaultListableBeanFactory

12. DefaultListableBeanFactory bean核心註冊中心

DefaultListableBeanFactory.java & 部分代碼截取

public void registerBeanDefinition(String beanName, BeanDefinition beanDefinition) throws BeanDefinitionStoreException {
	
	Assert.hasText(beanName, "Bean name must not be empty");
	Assert.notNull(beanDefinition, "BeanDefinition must not be null");
	
	if (beanDefinition instanceof AbstractBeanDefinition) {
		try {
			((AbstractBeanDefinition) beanDefinition).validate();
		}
		catch (BeanDefinitionValidationException ex) {
			throw new BeanDefinitionStoreException(beanDefinition.getResourceDescription(), beanName,
					"Validation of bean definition failed", ex);
		}
	}
	
	BeanDefinition existingDefinition = this.beanDefinitionMap.get(beanName);
	if (existingDefinition != null) {
		...
	}
	else {
		
		...
		
		else {
			// Still in startup registration phase
			this.beanDefinitionMap.put(beanName, beanDefinition);
			this.beanDefinitionNames.add(beanName);
			this.manualSingletonNames.remove(beanName);
		}
		this.frozenBeanDefinitionNames = null;
	}
	if (existingDefinition != null || containsSingleton(beanName)) {
		resetBeanDefinition(beanName);
	}
}
複製代碼
  • 源碼853行: 這就是最終咱們將 xml 中的配置信息註冊到了配置中心,beanDefinitionMap,同時還會寫入到 beanDefinitionNames

  • 看下最終的注入結果,嗯!咱們的盜墓挖到了一點寶物;

    微信公衆號:bugstack蟲洞棧 & bean註冊結果

5、綜上總結

  • 陳玉樓的盜墓(源碼分析),初步肯定了路線、墓室、幹掉了蜈蚣,今天你們勝利而歸,開始收拾整理裝備
  • 源碼分析真的就像盜墓同樣,分析前一切都是陌生的,一遍遍的分析後會從裏面不斷的獲取寶藏,這個寶藏的多少取決你對他的挖掘深度
  • 本次只是簡單的分析了一個 xml 中配置的 bean 註冊的過程,此時尚未真正的生成 bean,等下篇文章繼續分析

6、關注公衆號

微信公衆號:bugstack蟲洞棧
相關文章
相關標籤/搜索