Spring核心探索與總結(二):Spring容器初始化原始碼探索
Spring容器概述
容器是spring的核心,Spring容器使用DI管理構成應用的元件,它會建立相互協作的元件之間的關聯,負責建立物件,裝配它們,配置它們並管理它們的生命週期,從生存到死亡(在這裡,可能就是new 到 finalize())。
Spring容器不只有一個。Spring自帶了多個容器實現,可以歸納為兩種不同的型別:
1、bean工廠(由beanFactory介面定義)是最簡單的容器,提供基本的DI支援。
2、應用上下文(由ApplicationContext介面定義),基於BeanFactory構建,並且提供應用框架級別的服務。
ApplicationContext容器
相比bean工廠,ApplicationContext在實際的應用中顯得更受歡迎,下面著重介紹後者。
先來看下ApplicationContext的原始碼。
package org.springframework.context;
import org.springframework.beans.factory.HierarchicalBeanFactory;
import org.springframework.beans.factory.ListableBeanFactory;
import org.springframework.beans.factory.config.AutowireCapableBeanFactory;
import org.springframework.core.env.EnvironmentCapable;
import org.springframework.core.io.support.ResourcePatternResolver;
/**
* Central interface to provide configuration for an application.
* This is read-only while the application is running, but may be
* reloaded if the implementation supports this.
*
* <p>An ApplicationContext provides:
* <ul>
* <li>Bean factory methods for accessing application components.
* Inherited from {@link org.springframework.beans.factory.ListableBeanFactory}.
* <li>The ability to load file resources in a generic fashion.
* Inherited from the {@link org.springframework.core.io.ResourceLoader} interface.
* <li>The ability to publish events to registered listeners.
* Inherited from the {@link ApplicationEventPublisher} interface.
* <li>The ability to resolve messages, supporting internationalization.
* Inherited from the {@link MessageSource} interface.
* <li>Inheritance from a parent context. Definitions in a descendant context
* will always take priority. This means, for example, that a single parent
* context can be used by an entire web application, while each servlet has
* its own child context that is independent of that of any other servlet.
* </ul>
*
* <p>In addition to standard {@link org.springframework.beans.factory.BeanFactory}
* lifecycle capabilities, ApplicationContext implementations detect and invoke
* {@link ApplicationContextAware} beans as well as {@link ResourceLoaderAware},
* {@link ApplicationEventPublisherAware} and {@link MessageSourceAware} beans.
*
* @author Rod Johnson
* @author Juergen Hoeller
* @see ConfigurableApplicationContext
* @see org.springframework.beans.factory.BeanFactory
* @see org.springframework.core.io.ResourceLoader
*/
public interface ApplicationContext extends EnvironmentCapable, ListableBeanFactory, HierarchicalBeanFactory,
MessageSource, ApplicationEventPublisher, ResourcePatternResolver {
/**
* Return the unique id of this application context.
* @return the unique id of the context, or {@code null} if none
*/
String getId();
/**
* Return a name for the deployed application that this context belongs to.
* @return a name for the deployed application, or the empty String by default
*/
String getApplicationName();
/**
* Return a friendly name for this context.
* @return a display name for this context (never {@code null})
*/
String getDisplayName();
/**
* Return the timestamp when this context was first loaded.
* @return the timestamp (ms) when this context was first loaded
*/
long getStartupDate();
/**
* Return the parent context, or {@code null} if there is no parent
* and this is the root of the context hierarchy.
* @return the parent context, or {@code null} if there is no parent
*/
ApplicationContext getParent();
/**
* Expose AutowireCapableBeanFactory functionality for this context.
* <p>This is not typically used by application code, except for the purpose of
* initializing bean instances that live outside of the application context,
* applying the Spring bean lifecycle (fully or partly) to them.
* <p>Alternatively, the internal BeanFactory exposed by the
* {@link ConfigurableApplicationContext} interface offers access to the
* {@link AutowireCapableBeanFactory} interface too. The present method mainly
* serves as a convenient, specific facility on the ApplicationContext interface.
* <p><b>NOTE: As of 4.2, this method will consistently throw IllegalStateException
* after the application context has been closed.</b> In current Spring Framework
* versions, only refreshable application contexts behave that way; as of 4.2,
* all application context implementations will be required to comply.
* @return the AutowireCapableBeanFactory for this context
* @throws IllegalStateException if the context does not support the
* {@link AutowireCapableBeanFactory} interface, or does not hold an
* autowire-capable bean factory yet (e.g. if {@code refresh()} has
* never been called), or if the context has been closed already
* @see ConfigurableApplicationContext#refresh()
* @see ConfigurableApplicationContext#getBeanFactory()
*/
AutowireCapableBeanFactory getAutowireCapableBeanFactory() throws IllegalStateException;
}
ApplicationContext是spring中較高階的容器。和BeanFactory類似,它可以載入配置檔案中定義的bean,將所有的bean集中在一起,當有請求的時候分配bean。 另外,它增加了企業所需要的功能,比如,從屬性檔案從解析文字資訊和將事件傳遞給所指定的監聽器。這個容器在org.springframework.context.ApplicationContext介面中定義。ApplicationContext包含BeanFactory所有的功能,一般情況下,相對於BeanFactory,ApplicationContext會被推薦使用。但BeanFactory仍然可以在輕量級應用中使用,比如移動裝置或者基於applet的應用程式。
ApplicationContext介面關係
1、訪問應用程式元件的Bean工廠方法。繼承自ListableBeanFactory。
2、訪問資源。這一特性主要體現在ResourcePatternResolver介面上,對Resource和ResourceLoader的支援,這樣我們可以從不同地方得到Bean定義資源。這種抽象使使用者程式可以靈活地定義Bean定義資訊,尤其是從不同的IO途徑得到Bean定義資訊。這在介面上看不出來,不過一般來說,具體ApplicationContext都是繼承了DefaultResourceLoader的子類。因為DefaultResourceLoader是AbstractApplicationContext的基類。
3、支援應用事件。繼承了介面ApplicationEventPublisher,為應用環境引入了事件機制,這些事件和Bean的生命週期的結合為Bean的管理提供了便利。
4、解析訊息的能力,支援國際化。繼承MessageSource。
5、從父上下文繼承。在後代的定義將始終優先。這意味著,例如,一個上下文可以被整個Web應用程式使用,而每個servlet都可以使用獨立於任何其他servlet的子環境。
ApplicationContext繼承體系
ApplicationContext容器實現類
常用的如下:
AnnotationConfigApplicationContext
從一個或者多個基於java的配置類中載入Spring應用上下文。例如:
ApplicationContext annotationConfigApplicationContext = new AnnotationConfigApplicationContext(test.class);
AnnotationConfigWebApplicationContext
載入spring web應用上下文。
ClassPathXmlApplicationContext
從類的路徑下的一個或多個XML配置檔案中載入上下文,把應用上下文的定義檔案作為類資源
FileSystemXmlApplicationContext
和ClassPathXmlApplicationContext的區別在於後者是從指定的檔案系統路徑下查詢配置檔案,而前者是在所有的類路徑下查詢配置檔案。
例如:
ApplicationContext fileSystemXmlApplicationContext = new FileSystemXmlApplicationContext("c:/user/pro.xml");
ApplicationContext classPathXmlApplicationContext = new ClassPathXmlApplicationContext("pro.xml");
容器的運作原理
下面就上述提到的FileSystemXmlApplicationContext的容器實現類說明容器運作原理。
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;
/**
* Standalone XML application context, taking the context definition files
* from the file system or from URLs, interpreting plain paths as relative
* file system locations (e.g. "mydir/myfile.txt"). Useful for test harnesses
* as well as for standalone environments.
*
* <p><b>NOTE:</b> Plain paths will always be interpreted as relative
* to the current VM working directory, even if they start with a slash.
* (This is consistent with the semantics in a Servlet container.)
* <b>Use an explicit "file:" prefix to enforce an absolute file path.</b>
*
* <p>The config location defaults can be overridden via {@link #getConfigLocations},
* Config locations can either denote concrete files like "/myfiles/context.xml"
* or Ant-style patterns like "/myfiles/*-context.xml" (see the
* {@link org.springframework.util.AntPathMatcher} javadoc for pattern details).
*
* <p>Note: In case of multiple config locations, later bean definitions will
* override ones defined in earlier loaded files. This can be leveraged to
* deliberately override certain bean definitions via an extra XML file.
*
* <p><b>This is a simple, one-stop shop convenience ApplicationContext.
* Consider using the {@link GenericApplicationContext} class in combination
* with an {@link org.springframework.beans.factory.xml.XmlBeanDefinitionReader}
* for more flexible context setup.</b>
*
* @author Rod Johnson
* @author Juergen Hoeller
* @see #getResource
* @see #getResourceByPath
* @see GenericApplicationContext
*/
public class FileSystemXmlApplicationContext extends AbstractXmlApplicationContext {
/**
* Create a new FileSystemXmlApplicationContext for bean-style configuration.
* @see #setConfigLocation
* @see #setConfigLocations
* @see #afterPropertiesSet()
*/
public FileSystemXmlApplicationContext() {
}
/**
* Create a new FileSystemXmlApplicationContext for bean-style configuration.
* @param parent the parent context
* @see #setConfigLocation
* @see #setConfigLocations
* @see #afterPropertiesSet()
*/
public FileSystemXmlApplicationContext(ApplicationContext parent) {
super(parent);
}
/**
* Create a new FileSystemXmlApplicationContext, loading the definitions
* from the given XML file and automatically refreshing the context.
* @param configLocation file path
* @throws BeansException if context creation failed
*/
public FileSystemXmlApplicationContext(String configLocation) throws BeansException {
this(new String[] {configLocation}, true, null);
}
/**
* Create a new FileSystemXmlApplicationContext, loading the definitions
* from the given XML files and automatically refreshing the context.
* @param configLocations array of file paths
* @throws BeansException if context creation failed
*/
public FileSystemXmlApplicationContext(String... configLocations) throws BeansException {
this(configLocations, true, null);
}
/**
* Create a new FileSystemXmlApplicationContext with the given parent,
* loading the definitions from the given XML files and automatically
* refreshing the context.
* @param configLocations array of file paths
* @param parent the parent context
* @throws BeansException if context creation failed
*/
public FileSystemXmlApplicationContext(String[] configLocations, ApplicationContext parent) throws BeansException {
this(configLocations, true, parent);
}
/**
* Create a new FileSystemXmlApplicationContext, loading the definitions
* from the given XML files.
* @param configLocations array of file paths
* @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.
* @throws BeansException if context creation failed
* @see #refresh()
*/
public FileSystemXmlApplicationContext(String[] configLocations, boolean refresh) throws BeansException {
this(configLocations, refresh, null);
}
/**
* Create a new FileSystemXmlApplicationContext with the given parent,
* loading the definitions from the given XML files.
* @param configLocations array of file paths
* @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 FileSystemXmlApplicationContext(String[] configLocations, boolean refresh, ApplicationContext parent)
throws BeansException {
super(parent);
setConfigLocations(configLocations);
if (refresh) {
refresh();
}
}
/**
* Resolve resource paths as file system paths.
* <p>Note: Even if a given path starts with a slash, it will get
* interpreted as relative to the current VM working directory.
* This is consistent with the semantics in a Servlet container.
* @param path path to the resource
* @return Resource handle
* @see org.springframework.web.context.support.XmlWebApplicationContext#getResourceByPath
*/
@Override
protected Resource getResourceByPath(String path) {
if (path != null && path.startsWith("/")) {
path = path.substring(1);
}
return new FileSystemResource(path);
}
}
編寫測試類
public class FileSystemXmlApplicationContextTest{
public static void main(String[] args) {
ApplicationContext fileSystemXmlApplicationContext = new FileSystemXmlApplicationContext("c:/user/pro.xml");
fileSystemXmlApplicationContext.getBean("test", Test.class);
}
}
原始碼追蹤分析
/**
* Create a new FileSystemXmlApplicationContext with the given parent,
* loading the definitions from the given XML files.
* @param configLocations array of file paths
* @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 FileSystemXmlApplicationContext(String[] configLocations, boolean refresh, ApplicationContext parent)
throws BeansException {
super(parent);
setConfigLocations(configLocations);
if (refresh) {
refresh();
}
}
通過分析FileSystemXmlApplicationContext的原始碼可以知道,在建立FileSystemXmlApplicationContext容器時,構造方法做以下兩項重要工作:
首先,呼叫父類容器的構造方法(super(parent)方法)為容器設定好Bean資源載入器。
/**
* Create a new AbstractApplicationContext with the given parent context.
* @param parent the parent context
*/
public AbstractApplicationContext(ApplicationContext parent) {
this();
setParent(parent);
}
然後,setConfigLocations(configLocations);主要是載入配置檔案的路徑。
/**
* Set the config locations for this application context.
* <p>If not set, the implementation may use a default as appropriate.
*/
public void setConfigLocations(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;
}
}
最主要的是refresh();方法的實現。Ioc容器的refresh()過程,是個非常複雜的過程,但不同的容器實現這裡都是相似的,因此基類中就將他們封裝好了。
我們繼續跟進refresh()方法
@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 {
// Allows post-processing of the bean factory in context subclasses.
postProcessBeanFactory(beanFactory);
// Invoke factory processors registered as beans in the context.
invokeBeanFactoryPostProcessors(beanFactory);
// Register bean processors that intercept bean creation.
registerBeanPostProcessors(beanFactory);
// Initialize message source for this context.
initMessageSource();
// Initialize event multicaster for this context.
initApplicationEventMulticaster();
// Initialize other special beans in specific context subclasses.
onRefresh();
// Check for listener beans and register them.
registerListeners();
// Instantiate all remaining (non-lazy-init) singletons.
finishBeanFactoryInitialization(beanFactory);
// Last step: publish corresponding event.
finishRefresh();
}
catch (BeansException ex) {
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;
}
}
}
refresh定義在AbstractApplicationContext類中,它詳細描述了整個ApplicationContext的初始化過程,比如BeanFactory的更新、MessageSource和PostProcessor的註冊等。這裡看起來像是對ApplicationContext進行初始化的模版或執行提綱,這個執行過程為Bean的生命週期管理提供了條件。
/**
* Prepare this context for refreshing, setting its startup date and
* active flag as well as performing any initialization of property sources.
*/
protected void prepareRefresh() {
this.startupDate = System.currentTimeMillis();
this.active.set(true);
if (logger.isInfoEnabled()) {
logger.info("Refreshing " + this);
}
// Initialize any placeholder property sources in the context environment
initPropertySources();
// Validate that all properties marked as required are resolvable
// see ConfigurablePropertyResolver#setRequiredProperties
getEnvironment().validateRequiredProperties();
}
走到這裡prepareRefresh()方法主要是為準備重新整理容器, 獲取容器的當時時間, 同時給容器設定同步標識 。
繼續往下走obtainFreshBeanFactory();
/**
* Tell the subclass to refresh the internal bean factory.
* @return the fresh BeanFactory instance
* @see #refreshBeanFactory()
* @see #getBeanFactory()
*/
protected ConfigurableListableBeanFactory obtainFreshBeanFactory() {
refreshBeanFactory();
ConfigurableListableBeanFactory beanFactory = getBeanFactory();
if (logger.isDebugEnabled()) {
logger.debug("Bean factory for " + getDisplayName() + ": " + beanFactory);
}
return beanFactory;
}
看看refreshBeanFactory();幹了些什麼
/**
* This implementation performs an actual refresh of this context's underlying
* bean factory, shutting down the previous bean factory (if any) and
* initializing a fresh bean factory for the next phase of the context's lifecycle.
*/
@Override
protected final void refreshBeanFactory() throws BeansException {
if (hasBeanFactory()) { //如果已經有容器,銷燬容器中的bean,關閉容器
destroyBeans();
closeBeanFactory();
}
try {
//建立IoC容器
DefaultListableBeanFactory beanFactory = createBeanFactory();
beanFactory.setSerializationId(getId());
//對IoC容器進行定製化,如設定啟動引數,開啟註解的自動裝配等
customizeBeanFactory(beanFactory);
//呼叫載入Bean定義的方法,在當前類中只定義了抽象的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);
}
}
在這個方法中,先判斷BeanFactory是否存在,如果存在則先銷燬beans並關閉beanFactory,接著建立DefaultListableBeanFactory,並呼叫loadBeanDefinitions(beanFactory)裝載bean。
接著跟進loadBeanDefinitions()方法:
AbstractRefreshableApplicationContext中只定義了抽象的loadBeanDefinitions方法,容器真正呼叫的是其子類AbstractXmlApplicationContext對該方法的實現,AbstractXmlApplicationContext的主要原始碼如下:
/**
* Loads the bean definitions via an XmlBeanDefinitionReader.
* @see org.springframework.beans.factory.xml.XmlBeanDefinitionReader
* @see #initBeanDefinitionReader
* @see #loadBeanDefinitions
*/
@Override
protected void loadBeanDefinitions(DefaultListableBeanFactory beanFactory) throws BeansException, IOException {
//建立XmlBeanDefinitionReader,即建立Bean讀取器,並通過回撥設定到容器中去,容 器使用該讀取器讀取Bean定義資源
XmlBeanDefinitionReader beanDefinitionReader = new XmlBeanDefinitionReader(beanFactory);
//為Bean讀取器設定Spring資源載入器,AbstractXmlApplicationContext的
//祖先父類AbstractApplicationContext繼承DefaultResourceLoader,因此,容器本身也是一個資源載入器
beanDefinitionReader.setEnvironment(this.getEnvironment());
beanDefinitionReader.setResourceLoader(this);
//為Bean讀取器設定SAX xml解析器
beanDefinitionReader.setEntityResolver(new ResourceEntityResolver(this));
//當Bean讀取器讀取Bean定義的Xml資原始檔時,啟用Xml的校驗機制
initBeanDefinitionReader(beanDefinitionReader);
//Bean讀取器真正實現載入的方法
loadBeanDefinitions(beanDefinitionReader);
}
看下執行:
Xml Bean讀取器(XmlBeanDefinitionReader)呼叫其父類AbstractBeanDefinitionReader的 reader.loadBeanDefinitions方法讀取Bean定義資源。
下面將繼續研究讀取Bean定義資源的部分:
BeanDefinitionReader在其抽象父類AbstractBeanDefinitionReader中定義了載入過程
//過載方法,呼叫下面的loadBeanDefinitions(String, Set<Resource>);方法
public int loadBeanDefinitions(String location) throws BeanDefinitionStoreException {
return loadBeanDefinitions(location, null);
}
public int loadBeanDefinitions(String location, Set<Resource> actualResources) throws BeanDefinitionStoreException {
//獲取在IoC容器初始化過程中設定的資源載入器
ResourceLoader resourceLoader = getResourceLoader();
if (resourceLoader == null) {
throw new BeanDefinitionStoreException(
"Cannot import bean definitions from location [" + location + "]: no ResourceLoader available");
}
if (resourceLoader instanceof ResourcePatternResolver) {
try {
//將指定位置的Bean定義資原始檔解析為Spring IoC容器封裝的資源
//載入多個指定位置的Bean定義資原始檔
Resource[] resources = ((ResourcePatternResolver) resourceLoader).getResources(location);
//委派呼叫其子類XmlBeanDefinitionReader的方法,實現載入功能
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 {
//將指定位置的Bean定義資原始檔解析為Spring IoC容器封裝的資源
//載入單個指定位置的Bean定義資原始檔
Resource resource = resourceLoader.getResource(location);
//委派呼叫其子類XmlBeanDefinitionReader的方法,實現載入功能
int loadCount = loadBeanDefinitions(resource);
if (actualResources != null) {
actualResources.add(resource);
}
if (logger.isDebugEnabled()) {
logger.debug("Loaded " + loadCount + " bean definitions from location [" + location + "]");
}
return loadCount;
}
}
//過載方法,呼叫loadBeanDefinitions(String);
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;
}
loadBeanDefinitions(Resource…resources)方法和上面分析的3個方法類似,同樣也是呼叫XmlBeanDefinitionReader的loadBeanDefinitions方法。
從對AbstractBeanDefinitionReader的loadBeanDefinitions方法原始碼分析可以看出該方法做了以下兩件事:
首先,呼叫資源載入器的獲取資源方法resourceLoader.getResource(location),獲取到要載入的資源。
其次,真正執行載入功能是其子類XmlBeanDefinitionReader的loadBeanDefinitions方法。
XmlBeanDefinitionReader通過呼叫其父類DefaultResourceLoader的getResource方法獲取要載入的資源,其原始碼如下
//獲取Resource的具體實現方法
public Resource getResource(String location) {
Assert.notNull(location, "Location must not be null");
//如果是類路徑的方式,那需要使用ClassPathResource 來得到bean 檔案的資源物件
if (location.startsWith(CLASSPATH_URL_PREFIX)) {
return new ClassPathResource(location.substring(CLASSPATH_URL_PREFIX.length()), getClassLoader());
}
try {
// 如果是URL 方式,使用UrlResource 作為bean 檔案的資源物件
URL url = new URL(location);
return new UrlResource(url);
}
catch (MalformedURLException ex) {
}
//如果既不是classpath標識,又不是URL標識的Resource定位,則呼叫
//容器本身的getResourceByPath方法獲取Resource
return getResourceByPath(location);
}
FileSystemXmlApplicationContext容器提供了getResourceByPath方法的實現,就是為了處理既不是classpath標識,又不是URL標識的Resource定位這種情況。
protected Resource getResourceByPath(String path) {
if (path != null && path.startsWith("/")) {
path = path.substring(1);
}
//這裡使用檔案系統資源物件來定義bean 檔案
return new FileSystemResource(path);
}
這樣程式碼就回到了 FileSystemXmlApplicationContext 中來,他提供了FileSystemResource 來完成從檔案系統得到配置檔案的資源定義。
這樣,就可以從檔案系統路徑上對IOC 配置檔案進行載入 - 當然我們可以按照這個邏輯從任何地方載入,在Spring 中我們看到它提供 的各種資源抽象,比如ClassPathResource, URLResource,FileSystemResource 等來供我們使用。上面我們看到的是定位Resource 的一個過程,而這只是載入過程的一部分.
XmlBeanDefinitionReader載入Bean定義資源:
Bean定義的Resource得到了
繼續回到XmlBeanDefinitionReader的loadBeanDefinitions(Resource …)方法看到代表bean檔案的資源定義以後的載入過程。
//XmlBeanDefinitionReader載入資源的入口方法
public int loadBeanDefinitions(Resource resource) throws BeanDefinitionStoreException {
//將讀入的XML資源進行特殊編碼處理
return loadBeanDefinitions(new EncodedResource(resource));
}
//這裡是載入XML形式Bean定義資原始檔方法
public int loadBeanDefinitions(EncodedResource encodedResource) throws BeanDefinitionStoreException {
.......
try {
//將資原始檔轉為InputStream的IO流
InputStream inputStream = encodedResource.getResource().getInputStream();
try {
//從InputStream中得到XML的解析源
InputSource inputSource = new InputSource(inputStream);
if (encodedResource.getEncoding() != null) {
inputSource.setEncoding(encodedResource.getEncoding());
}
//這裡是具體的讀取過程
return doLoadBeanDefinitions(inputSource, encodedResource.getResource());
}
finally {
//關閉從Resource中得到的IO流
inputStream.close();
}
}
.........
26}
//從特定XML檔案中實際載入Bean定義資源的方法
protected int doLoadBeanDefinitions(InputSource inputSource, Resource resource)
throws BeanDefinitionStoreException {
try {
int validationMode = getValidationModeForResource(resource);
//將XML檔案轉換為DOM物件,解析過程由documentLoader實現
Document doc = this.documentLoader.loadDocument(
inputSource, this.entityResolver, this.errorHandler, validationMode, this.namespaceAware);
//這裡是啟動對Bean定義解析的詳細過程,該解析過程會用到Spring的Bean配置規則
return registerBeanDefinitions(doc, resource);
}
.......
}
通過原始碼分析,載入Bean定義資原始檔的最後一步是將Bean定義資源轉換為Document物件,該過程由documentLoader實現
DocumentLoader將Bean定義資源轉換成Document物件的原始碼如下:
//使用標準的JAXP將載入的Bean定義資源轉換成document物件
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);
//解析Spring的Bean定義資源
return builder.parse(inputSource);
}
protected DocumentBuilderFactory createDocumentBuilderFactory(int validationMode, boolean namespaceAware)
throws ParserConfigurationException {
//建立文件解析工廠
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
factory.setNamespaceAware(namespaceAware);
//設定解析XML的校驗
if (validationMode != XmlValidationModeDetector.VALIDATION_NONE) {
factory.setValidating(true);
if (validationMode == XmlValidationModeDetector.VALIDATION_XSD) {
factory.setNamespaceAware(true);
try {
factory.setAttribute(SCHEMA_LANGUAGE_ATTRIBUTE, XSD_SCHEMA_LANGUAGE);
}
catch (IllegalArgumentException ex) {
ParserConfigurationException pcex = new ParserConfigurationException(
"Unable to validate using XSD: Your JAXP provider [" + factory +
"] does not support XML Schema. Are you running on Java 1.4 with Apache Crimson? " +
"Upgrade to Apache Xerces (or Java 1.5) for full XSD support.");
pcex.initCause(ex);
throw pcex;
}
}
}
return factory;
}
該解析過程呼叫JavaEE標準的JAXP標準進行處理。
至此Spring IoC容器根據定位的Bean定義資原始檔,將其載入讀入並轉換成為Document物件過程完成。
接下來我們要繼續分析Spring IoC容器將載入的Bean定義資原始檔轉換為Document物件之後,是如何將其解析為Spring IoC管理的Bean物件並將其註冊到容器中的。
XmlBeanDefinitionReader類中的doLoadBeanDefinitions方法是從特定XML檔案中實際載入Bean定義資源的方法,該方法在載入Bean定義資源之後將其轉換為Document物件,接下來呼叫registerBeanDefinitions啟動Spring IoC容器對Bean定義的解析過程,registerBeanDefinitions方法原始碼如下:
//按照Spring的Bean語義要求將Bean定義資源解析並轉換為容器內部資料結構
public int registerBeanDefinitions(Document doc, Resource resource) throws BeanDefinitionStoreException {
//得到BeanDefinitionDocumentReader來對xml格式的BeanDefinition解析
BeanDefinitionDocumentReader documentReader = createBeanDefinitionDocumentReader();
//獲得容器中註冊的Bean數量
int countBefore = getRegistry().getBeanDefinitionCount();
//解析過程入口,這裡使用了委派模式,BeanDefinitionDocumentReader只是個介面,//具體的解析實現過程有實現類DefaultBeanDefinitionDocumentReader完成
documentReader.registerBeanDefinitions(doc, createReaderContext(resource));
//統計解析的Bean數量
return getRegistry().getBeanDefinitionCount() - countBefore;
}
//建立BeanDefinitionDocumentReader物件,解析Document物件
protected BeanDefinitionDocumentReader createBeanDefinitionDocumentReader() {
return BeanDefinitionDocumentReader.class.cast(BeanUtils.instantiateClass(this.documentReaderClass));
}
Bean定義資源的載入解析分為以下兩個過程:
首先,通過呼叫XML解析器將Bean定義資原始檔轉換得到Document物件,但是這些Document物件並沒有按照Spring的Bean規則進行解析。這一步是載入的過程
其次,在完成通用的XML解析之後,按照Spring的Bean規則對Document物件進行解析。
按照Spring的Bean規則對Document物件解析的過程是在介面BeanDefinitionDocumentReader的實現類DefaultBeanDefinitionDocumentReader中實現的。
BeanDefinitionDocumentReader介面通過registerBeanDefinitions方法呼叫其實現類DefaultBeanDefinitionDocumentReader對Document物件進行解析,解析的程式碼如下:
//根據Spring DTD對Bean的定義規則解析Bean定義Document物件
public void registerBeanDefinitions(Document doc, XmlReaderContext readerContext) {
//獲得XML描述符
this.readerContext = readerContext;
logger.debug("Loading bean definitions");
//獲得Document的根元素
Element root = doc.getDocumentElement();
//具體的解析過程由BeanDefinitionParserDelegate實現,
//BeanDefinitionParserDelegate中定義了Spring Bean定義XML檔案的各種元素
BeanDefinitionParserDelegate delegate = createHelper(readerContext, root);
//在解析Bean定義之前,進行自定義的解析,增強解析過程的可擴充套件性
preProcessXml(root);
//從Document的根元素開始進行Bean定義的Document物件
parseBeanDefinitions(root, delegate);
//在解析Bean定義之後,進行自定義的解析,增加解析過程的可擴充套件性
postProcessXml(root);
}
//建立BeanDefinitionParserDelegate,用於完成真正的解析過程
protected BeanDefinitionParserDelegate createHelper(XmlReaderContext readerContext, Element root) {
BeanDefinitionParserDelegate delegate = new BeanDefinitionParserDelegate(readerContext);
//BeanDefinitionParserDelegate初始化Document根元素
delegate.initDefaults(root);
return delegate;
}
//使用Spring的Bean規則從Document的根元素開始進行Bean定義的Document物件
protected void parseBeanDefinitions(Element root, BeanDefinitionParserDelegate delegate) {
//Bean定義的Document物件使用了Spring預設的XML名稱空間
if (delegate.isDefaultNamespace(root)) {
//獲取Bean定義的Document物件根元素的所有子節點
NodeList nl = root.getChildNodes();
for (int i = 0; i < nl.getLength(); i++) {
Node node = nl.item(i);
//獲得Document節點是XML元素節點
if (node instanceof Element) {
Element ele = (Element) node;
//Bean定義的Document的元素節點使用的是Spring預設的XML名稱空間
if (delegate.isDefaultNamespace(ele)) {
//使用Spring的Bean規則解析元素節點
parseDefaultElement(ele, delegate);
}
else {
//沒有使用Spring預設的XML名稱空間,則使用使用者自定義的解//析規則解析元素節點
delegate.parseCustomElement(ele);
}
}
}
}
else {
//Document的根節點沒有使用Spring預設的名稱空間,則使用使用者自定義的
//解析規則解析Document根節點
delegate.parseCustomElement(root);
}
}
//使用Spring的Bean規則解析Document元素節點
private void parseDefaultElement(Element ele, BeanDefinitionParserDelegate delegate) {
//如果元素節點是<Import>匯入元素,進行匯入解析
if (delegate.nodeNameEquals(ele, IMPORT_ELEMENT)) {
importBeanDefinitionResource(ele);
}
//如果元素節點是<Alias>別名元素,進行別名解析
else if (delegate.nodeNameEquals(ele, ALIAS_ELEMENT)) {
processAliasRegistration(ele);
}
//元素節點既不是匯入元素,也不是別名元素,即普通的<Bean>元素,
//按照Spring的B