Spring源碼--IOC容器實現(2)--BeanDefinition的Resource定位

一 IOC容器初始化過程概述

    IOC容器初始化是由上文提到的refresh()方法來啓動的,這個方法標誌着IOC容器正式啓動。

IOC容器初始化過程分爲三個過程:

1)BeanDefinition的Resource定位過程。

    這個Resource定位是指BeanDefinition資源定位,它由ResourceLoader通過統一的Resource

接口完成。這個定位過程就是容器尋找數據的過程,就像水桶要裝水首先需要找到水一樣。

2)BeanDefinition的載入和解析過程。

    這個過程就是根據上一步定位的Resource資源文件,把用戶定義好的Bean表示成IOC容器內部的

BeanDefinition數據結構。BeanDefinition實際就是POJO對象在IOC容器中的抽象,通過BeanDefinition

定義數據結構,使IOC容器能夠方便地對POJO對象也就是Bean進行管理。

3)向IOC容器註冊BeanDefinition的過程。

    這個過程是通過調用BeanDefinitionRegistry接口的實現來完成的,把載入過程生成的BeanDefinition向

IOC容器註冊。最終在IOC容器內部將BeanDefinition注入到一個HashMap中,IOC容器就是通過這個

HashMap來持有這些BeanDefinition數據的。

注意:

    這裏需要注意的是,上面談到的只是IOC容器的初始化過程,這個過程一般不包含Bean依賴注入的實現。

Bean的定義和依賴注入是兩個獨立的過程。依賴注入一般發生在第一次getBean()向容器索要Bean的時候,

但是如果配置了lazyinit,則初始化的時候這樣的Bean已經觸發了依賴注入。

這裏先分析IOC容器的第一個過程,BeanDefinition的Resource定位過程。

二 BeanDefinition的Resource定位過程

    一般我們通常使用的IOC容器有FileSystemXmlApplicationContext、ClassPathXmlApplicationContext、

XmlWebApplicationContext、WebApplicationContext等。下面以FileSystemXmlApplicationContext爲例,

分析Resource的定位過程。

FileSystemXmlApplicationContext應用:

// 根據配置文件創建IOC容器
ApplicationContext context =
     new FileSystemXmlApplicationContext("classpath:applicationContext.xml");
// 從容器中獲取Bean
ConferenceServiceImpl conferenceService = (ConferenceServiceImpl)context.getBean("conferenceService");
// 調用Bean方法
conferenceService.conference();

FileSystemXmlApplicationContext類圖:

"實線"代表extends,"虛線"代表implements。從類圖可以看到繼承了ApplicationContext,而ApplicationContext

又繼承了BeanFactory,所以FileSystemXmlApplicationContext具備了IOC的基本規範和一些高級特性。

在類圖的最右上方可以看到繼承了ResourceLoader,用以讀入以Resource定義的BeanDefinition的能力。

FileSystemXmlApplicationContext源碼:

package org.springframework.context.support;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.core.io.FileSystemResource;
import org.springframework.core.io.Resource;

public class FileSystemXmlApplicationContext extends AbstractXmlApplicationContext {
	public FileSystemXmlApplicationContext() {
	}
	public FileSystemXmlApplicationContext(ApplicationContext parent) {
		super(parent);
	}
	/**
	 * 根據用戶定義的Bean XML文件路徑,載入BeanDefinition,自動創建IOC容器
	 */
	public FileSystemXmlApplicationContext(String configLocation) throws BeansException {
		this(new String[] {configLocation}, true, null);
	}
	/**
	 * 根據用戶定義的多個Bean XML文件路徑,載入BeanDefinition,自動創建IOC容器
	 */
	public FileSystemXmlApplicationContext(String... configLocations) throws BeansException {
		this(configLocations, true, null);
	}
	/**
	 * 根據用戶定義的多個Bean XML文件路徑,載入BeanDefinition,自動創建IOC容器,允許指定自己的雙親IOC容器
	 */
	public FileSystemXmlApplicationContext(String[] configLocations, ApplicationContext parent) throws BeansException {
		this(configLocations, true, parent);
	}
	/**
	 * 是否允許自動刷新上下文
	 */
	public FileSystemXmlApplicationContext(String[] configLocations, boolean refresh) throws BeansException {
		this(configLocations, refresh, null);
	}
	/**
	 * 在對象初始化的過程中,調用refresh()方法啓動載入BeanDefinition過程
	 */
	public FileSystemXmlApplicationContext(String[] configLocations, boolean refresh, ApplicationContext parent)
			throws BeansException {
		super(parent);
		setConfigLocations(configLocations);
		if (refresh) {
			refresh();
		}
	}
	/**
	 * 根據用戶的xml構建Resource對象,這是一個模板方法,
	 * 在BeanDefinitionReader的loadBeanDefinition()方法中被調用。
	 */
	@Override
	protected Resource getResourceByPath(String path) {
		if (path != null && path.startsWith("/")) {
			path = path.substring(1);
		}
		return new FileSystemResource(path);
	}
}

    FileSystemXmlApplicationContext中有很多構造函數,實現了對參數configLocation進行處理,以XML文件方式

存在的BeanDefinition能夠得到有效處理。比如,實現了getResourceByPath()方法,這個是一個模板方法,是爲

讀取Resource服務的。在初始化FileSystemXmlApplicationContext的過程中,通過refresh()來啓動整個調用,

進入AbstractApplicationContext的refresh()方法。

AbstractApplicationContext.refresh()方法源碼:

@Override
public void refresh() throws BeansException, IllegalStateException {
	synchronized (this.startupShutdownMonitor) {
		// Prepare this context for refreshing.
		// 調用容器準備刷新的方法,設置容器的啓動時間爲當前時間,容器關閉狀態爲false,同時給容器設置同步標識
		prepareRefresh();

		// Tell the subclass to refresh the internal bean factory.
		// 告訴子類啓動refreshBeanFactory()方法,
		// Bean定義資源文件的載入從子類的refreshBeanFactory()方法啓動[***重點***]
		ConfigurableListableBeanFactory beanFactory = obtainFreshBeanFactory();

		// Prepare the bean factory for use in this context.
		// 爲BeanFactory配置容器特性,例如類加載器、事件處理器等
		prepareBeanFactory(beanFactory);

		try {
			// Allows post-processing of the bean factory in context subclasses.
			// 爲容器的某些子類指定特殊的BeanPost事件處理器,進行後置處理
			postProcessBeanFactory(beanFactory);

			// Invoke factory processors registered as beans in the context.
			// 調用BeanFactory的後置處理器,這些後置處理器是在Bean定義中向容器註冊的
			invokeBeanFactoryPostProcessors(beanFactory);

			// Register bean processors that intercept bean creation.
			// 爲BeanFactory註冊BeanPost事件處理器,BeanPostProcessor是Bean後置處理器,用於監聽容器觸發的事件
			registerBeanPostProcessors(beanFactory);

			// Initialize message source for this context.
			// 初始化信息源,和國際化相關
			initMessageSource();

			// Initialize event multicaster for this context.
			// 初始化容器事件傳播器
			initApplicationEventMulticaster();

			// Initialize other special beans in specific context subclasses.
			// 調用子類的某些特殊Bean初始化方法
			onRefresh();

			// Check for listener beans and register them.
			// 檢查監聽Bean並且將這些Bean向容器註冊
			registerListeners();

			// Instantiate all remaining (non-lazy-init) singletons.
			// 初始化所有剩餘的(non-lazy-init)單態Bean
			finishBeanFactoryInitialization(beanFactory);

			// Last step: publish corresponding event.
			// 初始化容器的生命週期事件處理器,併發布容器的生命週期事件,結束refresh過程
			finishRefresh();
		}

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

上面refresh()方法的源碼,是整個IOC容器初始化的過程。咱們這裏討論的是BeanDefinition的Resource資源的定位,

重點關注refresh()方法中的obtainFreshBeanFactory()方法,該方法也位於AbstractApplicationContext類中。

AbstractApplicationContext.obtainFreshBeanFactory()方法源碼:

protected ConfigurableListableBeanFactory obtainFreshBeanFactory() {
	refreshBeanFactory();
	ConfigurableListableBeanFactory beanFactory = getBeanFactory();
	if (logger.isDebugEnabled()) {
		logger.debug("Bean factory for " + getDisplayName() + ": " + beanFactory);
	}
	return beanFactory;
}

在上面的obtainFreshBeanFactory()方法中可以看到refreshBeanFactory()方法,是AbstractApplicationContext中的

一個抽象方法,委託給子類具體實現,方法簽名如下:

protected abstract void refreshBeanFactory() throws BeansException, IllegalStateException;

方法的具體實現在AbstractRefreshableApplicationContext中。

AbstractRefreshableApplicationContext.refreshBeanFactory()源碼:

@Override
protected final void refreshBeanFactory() throws BeansException {
	// 判斷如果已經建立了BeanFactory,則銷燬並關閉BeanFactory
	if (hasBeanFactory()) {
		destroyBeans();
		closeBeanFactory();
	}
	try {
	       // 創建IoC容器,這裏使用的是DefaultListableBeanFactory
		DefaultListableBeanFactory beanFactory = createBeanFactory();
		// 對IoC容器進行定製化,如設置啓動參數,開啓註解的自動裝配等
		beanFactory.setSerializationId(getId());
		customizeBeanFactory(beanFactory);
		/**
		 * 啓動對BeanDefinition的載入,這裏使用了一個委派模式,
		 * 在當前類中只定義了抽象的loadBeanDefinitions方法,具體的實現調用子類容器
		 */
		loadBeanDefinitions(beanFactory);
		synchronized (this.beanFactoryMonitor) {
			this.beanFactory = beanFactory;
		}
	}
	catch (IOException ex) {
		throw new ApplicationContextException("I/O error parsing bean definition source for " + getDisplayName(), ex);
	}
}

在refreshBeanFactory()方法中,可以看到loadBeanDefinitions()是AbstractRefreshableApplicationContext中的

一個抽象方法,委託給子類具體實現,方法簽名如下:

protected abstract void loadBeanDefinitions(DefaultListableBeanFactory beanFactory)
			throws BeansException, IOException;

loadBeanDefinitions()抽象方法有多個實現:

從FileSystemXmlApplicationContext類圖,可以知道選擇AbstractXmlApplicationContext中的實現,

因爲另外三個與FileSystemXmlApplicationContext沒有關係。

AbstractXmlApplicationContext.loadBeanDefinitions()方法源碼:

@Override
protected void loadBeanDefinitions(DefaultListableBeanFactory beanFactory) throws BeansException, IOException {
	// Create a new XmlBeanDefinitionReader for the given BeanFactory.
	// 根據BeanFactory容器,創建XmlBeanDefinitionReader讀取器
	XmlBeanDefinitionReader beanDefinitionReader = new XmlBeanDefinitionReader(beanFactory);

	// Configure the bean definition reader with this context's
	// resource loading environment.
	// 使用此上下文的資源加載環境配置Bean定義讀取器
	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.
	// 允許子類提供讀取器的自定義初始化,然後繼續加載bean定義信息
	initBeanDefinitionReader(beanDefinitionReader);
	loadBeanDefinitions(beanDefinitionReader);
}

繼續調用loadBeanDefinitions(),咱們現在目標就是定位BeanDEfinition的Resource看下方法源碼:

protected void loadBeanDefinitions(XmlBeanDefinitionReader reader) 
	throws BeansException, IOException {
	// 以Resource的方式獲得配置文件的資源位置
	Resource[] configResources = getConfigResources();
	if (configResources != null) {
		reader.loadBeanDefinitions(configResources);
	}
	// 以String的形式獲得配置文件位置
	String[] configLocations = getConfigLocations();
	if (configLocations != null) {
		reader.loadBeanDefinitions(configLocations);
	}
}

對於FileSystemXmlApplicationContext會走第二個if判斷, 接着看源碼。

AbstractBeanDefinitionReader.loadBeanDefinitions()方法源碼:

@Override
public int loadBeanDefinitions(String... locations) throws BeanDefinitionStoreException {
	// 如果locations爲空,則停止Resource資源定位
	Assert.notNull(locations, "Location array must not be null");
	int counter = 0;
	for (String location : locations) {
		// 根據路徑載入信息
		counter += loadBeanDefinitions(location);
	}
	return counter;
}

loadBeanDefinitions()方法繼續深入:

public int loadBeanDefinitions(String location, Set<Resource> actualResources) throws BeanDefinitionStoreException {
	// 這裏得到當前定義的ResourceLoader,默認的使用DefaultResourceLoader
	ResourceLoader resourceLoader = getResourceLoader();
	if (resourceLoader == null) {
		throw new BeanDefinitionStoreException(
				"Cannot import bean definitions from location [" + location + "]: no ResourceLoader available");
	}
	/**
	  * 這裏對Resource的路徑模式進行解析,得到需要的Resource集合,
	  * 這些Resource集合指向了我們定義好的BeanDefinition的信息,可以是多個文件。
	  */
	if (resourceLoader instanceof ResourcePatternResolver) {
		// Resource pattern matching available.
		try {
			// 調用DefaultResourceLoader的getResources完成具體的Resource定位
			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.
		// 通過ResourceLoader來完成位置定位
		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;
	}
}

ResourceLoader是一個接口類,其getResource()方法具體實現在DefaultResourceLoader,對於取得Resource的具體過程,

我們可以看下DefaultResourceLoader中getResource()方法的實現。

DefaultResourceLoader.getResource()源碼:

public Resource getResource(String location) {
    Assert.notNull(location, "Location must not be null");
    Iterator var2 = this.protocolResolvers.iterator();

    Resource resource;
    do {
        if (!var2.hasNext()) {
			// 處理所有/標識的Resource
            if (location.startsWith("/")) {
                return this.getResourceByPath(location);
            }
			// 處理所有帶有classpath標識的Resource
            if (location.startsWith("classpath:")) {
                return new ClassPathResource(location.substring("classpath:".length()), this.getClassLoader());
            }

            try {
				// 處理URL標識的Resource定位
                URL url = new URL(location);
                return new UrlResource(url);
            } catch (MalformedURLException var5) {
                return this.getResourceByPath(location);
            }
        }

        ProtocolResolver protocolResolver = (ProtocolResolver)var2.next();
        resource = protocolResolver.resolve(location, this);
    } while(resource == null);

    return resource;
}

在getResources()方法中,最顯眼的是getResourceByPath()方法,在一開始的時候提到過,它是一個模板方法,

DefaultResourceLoader.getResourceByPath()源碼:

protected Resource getResourceByPath(String path) {
	return new ClassPathContextResource(path, getClassLoader());
}

DefaultResourceLoader.getResourceByPath()實現類:

其中一個實現類就是FileSystemXmlApplicationContext,其方法簽名如下:

@Override
protected Resource getResourceByPath(String path) {
	if (path != null && path.startsWith("/")) {
		path = path.substring(1);
	}
	return new FileSystemResource(path);
}

通過該方法,返回一個FileSystemResource對象,該對象擴展自Resource,而Resource擴展自InputStreamSource。

FileSystemResource構造器:

public FileSystemResource(String path) {
    Assert.notNull(path, "Path must not be null");
    this.file = new File(path);
    this.path = StringUtils.cleanPath(path);
}

FileSystemResource類圖:

 

getResourceByPath方法調用過程:

通過FileSystemResource對象,Spring可以進行相關的I/O操作,完成BeanDefinition的Resource定位過程

    這裏只是分析了FileSystemXmlApplicationContext的容器下Resource定位過程,

如果是其他的ApplicationContext,那麼對應生成其他的Resource,比如ClassPathResource、

ServletContextResource等。關於Spring中Resource的種類,繼承關係如下:

這些接口對應不同的Resource實現代表着不同的一樣。

    以FileSystemXmlApplicationContext容器實現原理爲例,上面只是分析了BeanDefinition的Resource定位過程,

這個時候可以通過Resource對象來進行BeanDefinition的載入了。這裏完成了水桶裝水找水的過程,下一篇分析一下

水桶裝水的過程,也即BeanDefinition的載入和解析過程。

參考文獻:

1、《Spring技術內幕》

2、《Spring實戰》

3、Spring官網API

4、Spring源碼

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章