publicabstractclassAbstractXmlApplicationContextextendsAbstractRefreshableConfigApplicationContext{@OverrideprotectedvoidloadBeanDefinitions(DefaultListableBeanFactorybeanFactory)throwsBeansException,IOException{// Create a new XmlBeanDefinitionReader for the given BeanFactory.
// 创建BeanDefinitionReader
XmlBeanDefinitionReaderbeanDefinitionReader=newXmlBeanDefinitionReader(beanFactory);// Configure the bean definition reader with this context's
// resource loading environment.
beanDefinitionReader.setEnvironment(this.getEnvironment());beanDefinitionReader.setResourceLoader(this);beanDefinitionReader.setEntityResolver(newResourceEntityResolver(this));// Allow a subclass to provide custom initialization of the reader,
// then proceed with actually loading the bean definitions.
initBeanDefinitionReader(beanDefinitionReader);// TODO 关键点:加载BeanDefinition
loadBeanDefinitions(beanDefinitionReader);}}
publicabstractclassAbstractBeanDefinitionReaderimplementsBeanDefinitionReader,EnvironmentCapable{// 首先进入这个方法
@OverridepublicintloadBeanDefinitions(String...locations)throwsBeanDefinitionStoreException{Assert.notNull(locations,"Location array must not be null");intcount=0;// 一次解析配置文件,加载配置文件中定义的Bean。
for(Stringlocation:locations){count+=loadBeanDefinitions(location);}returncount;}}
publicclassDefaultBeanDefinitionDocumentReaderimplementsBeanDefinitionDocumentReader{// 第一步
protectedvoiddoRegisterBeanDefinitions(Elementroot){// 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.
BeanDefinitionParserDelegateparent=this.delegate;// BeanDefinitionParserDelegate中封装了预定义的很多标签属性
this.delegate=createDelegate(getReaderContext(),root,parent);// 根标签解析 NameSpace:http://www.springframework.org/schema/beans
if(this.delegate.isDefaultNamespace(root)){StringprofileSpec=root.getAttribute(PROFILE_ATTRIBUTE);if(StringUtils.hasText(profileSpec)){String[]specifiedProfiles=StringUtils.tokenizeToStringArray(profileSpec,BeanDefinitionParserDelegate.MULTI_VALUE_ATTRIBUTE_DELIMITERS);// We cannot use Profiles.of(...) since profile expressions are not supported
// in XML config. See SPR-12458 for details.
if(!getReaderContext().getEnvironment().acceptsProfiles(specifiedProfiles)){if(logger.isDebugEnabled()){logger.debug("Skipped XML bean definition file due to specified profiles ["+profileSpec+"] not matching: "+getReaderContext().getResource());}return;}}}// 钩子方法,解析xml注册BeanDefinition之前调用,可以不看
preProcessXml(root);// TODO 解析xml,注册BeanDefinition
parseBeanDefinitions(root,this.delegate);// 钩子方法,解析xml注册BeanDefinition之后调用,可以不看
postProcessXml(root);this.delegate=parent;}// 第二步
protectedvoidparseBeanDefinitions(Elementroot,BeanDefinitionParserDelegatedelegate){// Spring根标签,NameSpace:http://www.springframework.org/schema/beans
// 这里循环document中的元素,进行解析默认标签及自定义标签
StringtagName=root.getTagName();if(delegate.isDefaultNamespace(root)){NodeListnl=root.getChildNodes();for(inti=0;i<nl.getLength();i++){Nodenode=nl.item(i);if(nodeinstanceofElement){Elementele=(Element)node;if(delegate.isDefaultNamespace(ele)){logger.debug("delegate.isDefaultNamespace(root):true,解析默认标签 "+tagName);// TODO 关键点:解析默认标签
parseDefaultElement(ele,delegate);}else{logger.debug("delegate.isDefaultNamespace(root):true,解析自定义标签 "+tagName);// TODO 关键点:解析自定义标签
delegate.parseCustomElement(ele);}}}}else{logger.debug("delegate.isDefaultNamespace(root):false,解析自定义标签 "+tagName);// TODO 关键点:解析自定义标签
delegate.parseCustomElement(root);}}}
publicclassBeanDefinitionParserDelegate{@NullablepublicAbstractBeanDefinitionparseBeanDefinitionElement(Elementele,StringbeanName,@NullableBeanDefinitioncontainingBean){this.parseState.push(newBeanEntry(beanName));// bean标签中的class属性
StringclassName=null;if(ele.hasAttribute(CLASS_ATTRIBUTE)){className=ele.getAttribute(CLASS_ATTRIBUTE).trim();}// bean标签中的parent属性
Stringparent=null;if(ele.hasAttribute(PARENT_ATTRIBUTE)){parent=ele.getAttribute(PARENT_ATTRIBUTE);}try{// TODO 重点:创建BeanDefinition,设置parent、beanClass、beanClassName属性。
// bean标签的bean均定义为:GenericBeanDefinition
AbstractBeanDefinitionbd=createBeanDefinition(className,parent);// TODO 重点:解析element并设置BeanDefinition中的属性值
parseBeanDefinitionAttributes(ele,beanName,containingBean,bd);bd.setDescription(DomUtils.getChildElementValueByTagName(ele,DESCRIPTION_ELEMENT));// 解析meta标签、lookupOverride子标签、replaceMethod子标签
parseMetaElements(ele,bd);parseLookupOverrideSubElements(ele,bd.getMethodOverrides());parseReplacedMethodSubElements(ele,bd.getMethodOverrides());// 解析构造函数参数、property参数、qualifier参数
parseConstructorArgElements(ele,bd);parsePropertyElements(ele,bd);parseQualifierElements(ele,bd);bd.setResource(this.readerContext.getResource());bd.setSource(extractSource(ele));returnbd;}catch(ClassNotFoundExceptionex){error("Bean class ["+className+"] not found",ele,ex);}catch(NoClassDefFoundErrorerr){error("Class that bean class ["+className+"] depends on not found",ele,err);}catch(Throwableex){error("Unexpected failure during bean definition parsing",ele,ex);}finally{this.parseState.pop();}returnnull;}}
publicclassBeanDefinitionParserDelegate{@NullablepublicBeanDefinitionparseCustomElement(Elementele,@NullableBeanDefinitioncontainingBd){// SPI方式获取namespaceUri
StringnamespaceUri=getNamespaceURI(ele);if(namespaceUri==null){returnnull;}// 获取NamespaceHandler,这里面调用了NamespaceHandler的init方法
NamespaceHandlerhandler=this.readerContext.getNamespaceHandlerResolver().resolve(namespaceUri);if(handler==null){error("Unable to locate Spring NamespaceHandler for XML schema namespace ["+namespaceUri+"]",ele);returnnull;}returnhandler.parse(ele,newParserContext(this.readerContext,this,containingBd));}}
publicclassDefaultNamespaceHandlerResolverimplementsNamespaceHandlerResolver{@Override@NullablepublicNamespaceHandlerresolve(StringnamespaceUri){// 从缓存中获取,如果存在,直接返回,如果不存在则创建
Map<String,Object>handlerMappings=getHandlerMappings();ObjecthandlerOrClassName=handlerMappings.get(namespaceUri);if(handlerOrClassName==null){returnnull;}elseif(handlerOrClassNameinstanceofNamespaceHandler){return(NamespaceHandler)handlerOrClassName;}else{StringclassName=(String)handlerOrClassName;try{// 加载Class
Class<?>handlerClass=ClassUtils.forName(className,this.classLoader);if(!NamespaceHandler.class.isAssignableFrom(handlerClass)){thrownewFatalBeanException("Class ["+className+"] for namespace ["+namespaceUri+"] does not implement the ["+NamespaceHandler.class.getName()+"] interface");}// TODO 重点:实例化NamespaceHandler,调用init方法,放入缓存。这里是一个扩展点,所有的自定义标签都要提供对应的NamespaceHandler
// spring.handler文件中定义了很多内置的NamespaceHandler,通过SPI的方式加载、实例化
NamespaceHandlernamespaceHandler=(NamespaceHandler)BeanUtils.instantiateClass(handlerClass);namespaceHandler.init();handlerMappings.put(namespaceUri,namespaceHandler);returnnamespaceHandler;}catch(ClassNotFoundExceptionex){thrownewFatalBeanException("Could not find NamespaceHandler class ["+className+"] for namespace ["+namespaceUri+"]",ex);}catch(LinkageErrorerr){thrownewFatalBeanException("Unresolvable class definition for NamespaceHandler class ["+className+"] for namespace ["+namespaceUri+"]",err);}}}}
回到BeanDefinitionParserDelegate.parseCustomElement方法,最后一行handler.parse(ele, new ParserContext(this.readerContext, this, containingBd)),调用了对应的处理类的parse方法(前面有提到的一个parsers成员变量,标签属性名-处理类实例映射)