SpringIOC 容器對 Bean 定義資源的載入是從 refresh()函數開始的,refresh()是一個模闆方法, refresh()方法的作用是:在建立 IOC 容器前,如果已經有容器存在,則需要把已有的容器銷毀和關閉, 以保證在 refresh 之後使用的是建立立起來的 IOC 容器。refresh 的作用類似于對 IOC 容器的重新開機, 在建立立好的容器中對容器進行初始化,對 Bean 定義資源進行載入
包:package org.springframework.context.support;
類:AbstractApplicationContext
@Override
public void refresh() throws BeansException, IllegalStateException {
//startupShutdownMonitor對象在spring環境重新整理和銷毀的時候都會用到,確定重新整理和銷毀不會同時執行
synchronized (this.startupShutdownMonitor) {
// Prepare this context for refreshing.
//調用容器準備重新整理的方法,擷取容器的當時時間,同時給容器設定同步辨別
// 準備工作,例如記錄事件,設定标志,檢查環境變量等,并有留給子類擴充的位置,用來将屬性加入到applicationContext中
prepareRefresh();
// Tell the subclass to refresh the internal bean factory.
//告訴子類啟動refreshBeanFactory()方法,Bean定義資源檔案的載入從
//子類的refreshBeanFactory()方法啟動
// 建立beanFactory,這個對象作為applicationContext的成員變量,可以被applicationContext拿來用,
// 并且解析資源(例如xml檔案),取得bean的定義,放在beanFactory中
ConfigurableListableBeanFactory beanFactory = obtainFreshBeanFactory();
// Prepare the bean factory for use in this context.
//為BeanFactory配置容器特性,例如類加載器、事件處理器等
// 對beanFactory做一些設定,例如類加載器、SPEL解析器、指定bean的某些類型的成員變量對應某些對象.
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.
//調用所有注冊的BeanFactoryPostProcessor的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.
//為事件傳播器注冊事件監聽器.
registerListeners();
// Instantiate all remaining (non-lazy-init) singletons.
//初始化所有剩餘的單例Bean
finishBeanFactoryInitialization(beanFactory);
// Last step: publish corresponding event.
//初始化容器的生命周期事件處理器,并釋出容器的生命周期事件
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.
//銷毀已建立的Bean
destroyBeans();
// Reset 'active' flag.
//取消refresh操作,重置容器的同步辨別.
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();
}
}
}
(1): prepareRefresh();(和refresh()在同一個類AbstractApplicationContext中)
protected void prepareRefresh() {
// 設定初始化開始的時間
this.startupDate = System.currentTimeMillis();
// 設定context的關閉狀态為false
this.closed.set(false);
// 設定context的活動狀态是true
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
// 驗證對應的key在環境變量中是否存在,如果不存在就抛異常
getEnvironment().validateRequiredProperties();
// Allow for the collection of early ApplicationEvents,
// to be published once the multicaster is available...
// earlyApplicationEvents存放早起的一些事件。
this.earlyApplicationEvents = new LinkedHashSet<>();
}
protected void initPropertySources() {
// For subclasses: do nothing by default.
}
(2): obtainFreshBeanFactory() (和refresh()在同一個類AbstractApplicationContext中)
ConfigurableListableBeanFactory beanFactory = obtainFreshBeanFactory();
protected ConfigurableListableBeanFactory obtainFreshBeanFactory() {
//這裡使用了委派設計模式,父類定義了抽象的refreshBeanFactory()方法,具體實作調用子類容器的refreshBeanFactory()方法
refreshBeanFactory();
// 擷取refreshBeanFactory()實作類中建立的BeanFactory對象
ConfigurableListableBeanFactory beanFactory = getBeanFactory();
if (logger.isDebugEnabled()) {
logger.debug("Bean factory for " + getDisplayName() + ": " + beanFactory);
}
return beanFactory;
}
refresh()->obtainFreshBeanFactory()->refreshBeanFactory();方法
protected final void refreshBeanFactory() throws BeansException {
//如果已經有容器,銷毀容器中的bean,關閉容器
if (hasBeanFactory()) {
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);
}
}
loadBeanDefinitions:此處可以分為兩種:
1.xml檔案解析:
2.注解方法的解析:
此處分析XML檔案解析的方法。注解方法的解析看:Spring的IOC容器初始化源碼分析四:載入注解Bean
loadBeanDefinitions(beanFactory);
包: package org.springframework.context.support;
類: AbstractXmlApplicationContext
protected void loadBeanDefinitions(DefaultListableBeanFactory beanFactory) throws BeansException, IOException {
// Create a new XmlBeanDefinitionReader for the given BeanFactory.
//建立XmlBeanDefinitionReader,即建立Bean讀取器,并通過回調設定到容器中去,容器使用該讀取器讀取Bean定義資源
XmlBeanDefinitionReader beanDefinitionReader = new XmlBeanDefinitionReader(beanFactory);
// Configure the bean definition reader with this context's
// resource loading environment.
//為Bean讀取器設定Spring資源加載器,AbstractXmlApplicationContext的
//祖先父類AbstractApplicationContext繼承DefaultResourceLoader,是以,容器本身也是一個資源加載器
beanDefinitionReader.setEnvironment(this.getEnvironment());
beanDefinitionReader.setResourceLoader(this);
//為Bean讀取器設定SAX xml解析器
beanDefinitionReader.setEntityResolver(new ResourceEntityResolver(this));
// Allow a subclass to provide custom initialization of the reader,
// then proceed with actually loading the bean definitions.
//當Bean讀取器讀取Bean定義的Xml資源檔案時,啟用Xml的校驗機制
initBeanDefinitionReader(beanDefinitionReader);
//Bean讀取器真正實作加載的方法
loadBeanDefinitions(beanDefinitionReader);
}
loadBeanDefinitions同一個類中
//Xml Bean讀取器加載Bean定義資源
protected void loadBeanDefinitions(XmlBeanDefinitionReader reader) throws BeansException, IOException {
//擷取Bean定義資源的定位
Resource[] configResources = getConfigResources();
if (configResources != null) {
//Xml Bean讀取器調用其父類AbstractBeanDefinitionReader讀取定位
//的Bean定義資源
reader.loadBeanDefinitions(configResources);
}
//如果子類中擷取的Bean定義資源定位為空,則擷取FileSystemXmlApplicationContext構造方法中setConfigLocations方法設定的資源
String[] configLocations = getConfigLocations();
if (configLocations != null) {
//Xml Bean讀取器調用其父類AbstractBeanDefinitionReader讀取定位
//的Bean定義資源
reader.loadBeanDefinitions(configLocations);
}
}
loadBeanDefinitions方法:
類:package org.springframework.beans.factory.support;
包:AbstractBeanDefinitionReader
//重載方法,調用loadBeanDefinitions(String);
@Override
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(String, Set<Resource>);方法
@Override
public int loadBeanDefinitions(String location) throws BeanDefinitionStoreException {
return loadBeanDefinitions(location, null);
}
public int loadBeanDefinitions(String location, @Nullable 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) {
// Resource pattern matching available.
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 {
// Can only load single resources by absolute URL.
//将指定位置的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;
}
}
//擷取Resource的具體實作方法
@Override
public Resource getResource(String location) {
Assert.notNull(location, "Location must not be null");
for (ProtocolResolver protocolResolver : this.protocolResolvers) {
Resource resource = protocolResolver.resolve(location, this);
if (resource != null) {
return resource;
}
}
//如果是類路徑的方式,那需要使用ClassPathResource 來得到bean 檔案的資源對象
if (location.startsWith("/")) {
return getResourceByPath(location);
}
else if (location.startsWith(CLASSPATH_URL_PREFIX)) {
return new ClassPathResource(location.substring(CLASSPATH_URL_PREFIX.length()), getClassLoader());
}
else {
try {
// Try to parse the location as a URL...
// 如果是URL 方式,使用UrlResource 作為bean 檔案的資源對象
URL url = new URL(location);
return (ResourceUtils.isFileURL(url) ? new FileUrlResource(url) : new UrlResource(url));
}
catch (MalformedURLException ex) {
// No URL -> resolve as resource path.
//如果既不是classpath辨別,又不是URL辨別的Resource定位,則調用
//容器本身的getResourceByPath方法擷取Resource
return getResourceByPath(location);
}
}
}
protected Resource getResourceByPath(String path) {
return new ClassPathContextResource(path, getClassLoader());
}
public int loadBeanDefinitions(Resource... resources) throws BeanDefinitionStoreException {
Assert.notNull(resources, "Resource array must not be null");
int counter = 0;
for (Resource resource : resources) {
counter += loadBeanDefinitions(resource);
}
return counter;
}
loadBeanDefinitions
public int loadBeanDefinitions(Resource resource) throws BeanDefinitionStoreException {
//将讀入的XML資源進行特殊編碼處理
return loadBeanDefinitions(new EncodedResource(resource));
}
//這裡是載入XML形式Bean定義資源檔案方法
public int loadBeanDefinitions(EncodedResource encodedResource) throws BeanDefinitionStoreException {
Assert.notNull(encodedResource, "EncodedResource must not be null");
if (logger.isInfoEnabled()) {
logger.info("Loading XML bean definitions from " + encodedResource.getResource());
}
Set<EncodedResource> currentResources = this.resourcesCurrentlyBeingLoaded.get();
if (currentResources == null) {
currentResources = new HashSet<>(4);
this.resourcesCurrentlyBeingLoaded.set(currentResources);
}
if (!currentResources.add(encodedResource)) {
throw new BeanDefinitionStoreException(
"Detected cyclic loading of " + encodedResource + " - check your import definitions!");
}
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();
}
}
catch (IOException ex) {
throw new BeanDefinitionStoreException(
"IOException parsing XML document from " + encodedResource.getResource(), ex);
}
finally {
currentResources.remove(encodedResource);
if (currentResources.isEmpty()) {
this.resourcesCurrentlyBeingLoaded.remove();
}
}
}
doLoadBeanDefinitions
//從特定XML檔案中實際載入Bean定義資源的方法
protected int doLoadBeanDefinitions(InputSource inputSource, Resource resource)
throws BeanDefinitionStoreException {
try {
//将XML檔案轉換為DOM對象,解析過程由documentLoader實作
Document doc = doLoadDocument(inputSource, resource);
//這裡是啟動對Bean定義解析的詳細過程,該解析過程會用到Spring的Bean配置規則
return registerBeanDefinitions(doc, resource);
}
catch (BeanDefinitionStoreException ex) {
throw ex;
}
catch (SAXParseException ex) {
throw new XmlBeanDefinitionStoreException(resource.getDescription(),
"Line " + ex.getLineNumber() + " in XML document from " + resource + " is invalid", ex);
}
catch (SAXException ex) {
throw new XmlBeanDefinitionStoreException(resource.getDescription(),
"XML document from " + resource + " is invalid", ex);
}
catch (ParserConfigurationException ex) {
throw new BeanDefinitionStoreException(resource.getDescription(),
"Parser configuration exception parsing XML from " + resource, ex);
}
catch (IOException ex) {
throw new BeanDefinitionStoreException(resource.getDescription(),
"IOException parsing XML document from " + resource, ex);
}
catch (Throwable ex) {
throw new BeanDefinitionStoreException(resource.getDescription(),
"Unexpected exception parsing XML document from " + resource, ex);
}
}
protected Document doLoadDocument(InputSource inputSource, Resource resource) throws Exception {
return this.documentLoader.loadDocument(inputSource, getEntityResolver(), this.errorHandler,
getValidationModeForResource(resource), isNamespaceAware());
}
//使用标準的JAXP将載入的Bean定義資源轉換成document對象
@Override
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) {
// Enforce namespace aware for 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;
}
//按照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;
}
//根據Spring DTD對Bean的定義規則解析Bean定義Document對象
@Override
public void registerBeanDefinitions(Document doc, XmlReaderContext readerContext) {
//獲得XML描述符
this.readerContext = readerContext;
logger.debug("Loading bean definitions");
//獲得Document的根元素
Element root = doc.getDocumentElement();
doRegisterBeanDefinitions(root);
}
protected void doRegisterBeanDefinitions(Element root) {
// Any nested <beans> elements will cause recursion in this method. In
// order to propagate and preserve <beans> default-* attributes correctly,
// keep track of the current (parent) delegate, which may be null. Create
// the new (child) delegate with a reference to the parent for fallback purposes,
// then ultimately reset this.delegate back to its original (parent) reference.
// this behavior emulates a stack of delegates without actually necessitating one.
//具體的解析過程由BeanDefinitionParserDelegate實作,
//BeanDefinitionParserDelegate中定義了Spring Bean定義XML檔案的各種元素
BeanDefinitionParserDelegate parent = this.delegate;
this.delegate = createDelegate(getReaderContext(), root, parent);
if (this.delegate.isDefaultNamespace(root)) {
String profileSpec = root.getAttribute(PROFILE_ATTRIBUTE);
if (StringUtils.hasText(profileSpec)) {
String[] specifiedProfiles = StringUtils.tokenizeToStringArray(
profileSpec, BeanDefinitionParserDelegate.MULTI_VALUE_ATTRIBUTE_DELIMITERS);
if (!getReaderContext().getEnvironment().acceptsProfiles(specifiedProfiles)) {
if (logger.isInfoEnabled()) {
logger.info("Skipped XML bean definition file due to specified profiles [" + profileSpec +
"] not matching: " + getReaderContext().getResource());
}
return;
}
}
}
//在解析Bean定義之前,進行自定義的解析,增強解析過程的可擴充性
preProcessXml(root);
//從Document的根元素開始進行Bean定義的Document對象
parseBeanDefinitions(root, this.delegate);
//在解析Bean定義之後,進行自定義的解析,增加解析過程的可擴充性
postProcessXml(root);
this.delegate = parent;
}
//建立BeanDefinitionParserDelegate,用于完成真正的解析過程
protected BeanDefinitionParserDelegate createDelegate(
XmlReaderContext readerContext, Element root, @Nullable BeanDefinitionParserDelegate parentDelegate) {
BeanDefinitionParserDelegate delegate = new BeanDefinitionParserDelegate(readerContext);
//BeanDefinitionParserDelegate初始化Document根元素
delegate.initDefaults(root, parentDelegate);
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);
}
}
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的Bean規則解析元素
else if (delegate.nodeNameEquals(ele, BEAN_ELEMENT)) {
processBeanDefinition(ele, delegate);
}
else if (delegate.nodeNameEquals(ele, NESTED_BEANS_ELEMENT)) {
// recurse
doRegisterBeanDefinitions(ele);
}
}
//解析<Import>導入元素,從給定的導入路徑加載Bean定義資源到Spring IoC容器中
protected void importBeanDefinitionResource(Element ele) {
//擷取給定的導入元素的location屬性
String location = ele.getAttribute(RESOURCE_ATTRIBUTE);
//如果導入元素的location屬性值為空,則沒有導入任何資源,直接傳回
if (!StringUtils.hasText(location)) {
getReaderContext().error("Resource location must not be empty", ele);
return;
}
// Resolve system properties: e.g. "${user.dir}"
//使用系統變量值解析location屬性值
location = getReaderContext().getEnvironment().resolveRequiredPlaceholders(location);
Set<Resource> actualResources = new LinkedHashSet<>(4);
// Discover whether the location is an absolute or relative URI
//辨別給定的導入元素的location是否是絕對路徑
boolean absoluteLocation = false;
try {
absoluteLocation = ResourcePatternUtils.isUrl(location) || ResourceUtils.toURI(location).isAbsolute();
}
catch (URISyntaxException ex) {
// cannot convert to an URI, considering the location relative
// unless it is the well-known Spring prefix "classpath*:"
//給定的導入元素的location不是絕對路徑
}
// Absolute or relative?
//給定的導入元素的location是絕對路徑
if (absoluteLocation) {
try {
//使用資源讀入器加載給定路徑的Bean定義資源
int importCount = getReaderContext().getReader().loadBeanDefinitions(location, actualResources);
if (logger.isDebugEnabled()) {
logger.debug("Imported " + importCount + " bean definitions from URL location [" + location + "]");
}
}
catch (BeanDefinitionStoreException ex) {
getReaderContext().error(
"Failed to import bean definitions from URL location [" + location + "]", ele, ex);
}
}
else {
// No URL -> considering resource location as relative to the current file.
//給定的導入元素的location是相對路徑
try {
int importCount;
//将給定導入元素的location封裝為相對路徑資源
Resource relativeResource = getReaderContext().getResource().createRelative(location);
//封裝的相對路徑資源存在
if (relativeResource.exists()) {
//使用資源讀入器加載Bean定義資源
importCount = getReaderContext().getReader().loadBeanDefinitions(relativeResource);
actualResources.add(relativeResource);
}
//封裝的相對路徑資源不存在
else {
//擷取Spring IOC容器資源讀入器的基本路徑
String baseLocation = getReaderContext().getResource().getURL().toString();
//根據Spring IOC容器資源讀入器的基本路徑加載給定導入路徑的資源
importCount = getReaderContext().getReader().loadBeanDefinitions(
StringUtils.applyRelativePath(baseLocation, location), actualResources);
}
if (logger.isDebugEnabled()) {
logger.debug("Imported " + importCount + " bean definitions from relative location [" + location + "]");
}
}
catch (IOException ex) {
getReaderContext().error("Failed to resolve current resource location", ele, ex);
}
catch (BeanDefinitionStoreException ex) {
getReaderContext().error("Failed to import bean definitions from relative location [" + location + "]",
ele, ex);
}
}
Resource[] actResArray = actualResources.toArray(new Resource[actualResources.size()]);
//在解析完<Import>元素之後,發送容器導入其他資源處理完成事件
getReaderContext().fireImportProcessed(location, actResArray, extractSource(ele));
}
//解析<Alias>别名元素,為Bean向Spring IoC容器注冊别名
protected void processAliasRegistration(Element ele) {
//擷取<Alias>别名元素中name的屬性值
String name = ele.getAttribute(NAME_ATTRIBUTE);
//擷取<Alias>别名元素中alias的屬性值
String alias = ele.getAttribute(ALIAS_ATTRIBUTE);
boolean valid = true;
//<alias>别名元素的name屬性值為空
if (!StringUtils.hasText(name)) {
getReaderContext().error("Name must not be empty", ele);
valid = false;
}
//<alias>别名元素的alias屬性值為空
if (!StringUtils.hasText(alias)) {
getReaderContext().error("Alias must not be empty", ele);
valid = false;
}
if (valid) {
try {
//向容器的資源讀入器注冊别名
getReaderContext().getRegistry().registerAlias(name, alias);
}
catch (Exception ex) {
getReaderContext().error("Failed to register alias '" + alias +
"' for bean with name '" + name + "'", ele, ex);
}
//在解析完<Alias>元素之後,發送容器别名處理完成事件
getReaderContext().fireAliasRegistered(name, alias, extractSource(ele));
}
}
//解析Bean定義資源Document對象的普通元素
protected void processBeanDefinition(Element ele, BeanDefinitionParserDelegate delegate) {
BeanDefinitionHolder bdHolder = delegate.parseBeanDefinitionElement(ele);
// BeanDefinitionHolder是對BeanDefinition的封裝,即Bean定義的封裝類
//對Document對象中<Bean>元素的解析由BeanDefinitionParserDelegate實作
// BeanDefinitionHolder bdHolder = delegate.parseBeanDefinitionElement(ele);
if (bdHolder != null) {
bdHolder = delegate.decorateBeanDefinitionIfRequired(ele, bdHolder);
try {
// Register the final decorated instance.
//向Spring IOC容器注冊解析得到的Bean定義,這是Bean定義向IOC容器注冊的入口
BeanDefinitionReaderUtils.registerBeanDefinition(bdHolder, getReaderContext().getRegistry());
}
catch (BeanDefinitionStoreException ex) {
getReaderContext().error("Failed to register bean definition with name '" +
bdHolder.getBeanName() + "'", ele, ex);
}
// Send registration event.
//在完成向Spring IOC容器注冊解析得到的Bean定義之後,發送注冊事件
getReaderContext().fireComponentRegistered(new BeanComponentDefinition(bdHolder));
}
}
BeanDefinitionParserDelegate
refresh()->obtainFreshBeanFactory()->getBeanFactory()
擷取refreshBeanFactory()實作類中建立的BeanFactory對象
@Override
public final ConfigurableListableBeanFactory getBeanFactory() {
synchronized (this.beanFactoryMonitor) {
if (this.beanFactory == null) {
throw new IllegalStateException("BeanFactory not initialized or already closed - " +
"call 'refresh' before accessing beans via the ApplicationContext");
}
return this.beanFactory;
}
}