publicabstractclassAbstractXmlApplicationContextextendsAbstractRefreshableConfigApplicationContext{@OverrideprotectedvoidloadBeanDefinitions(DefaultListableBeanFactorybeanFactory)throwsBeansException,IOException{// Create a new XmlBeanDefinitionReader for the given BeanFactory.// 创建BeanDefinitionReaderXmlBeanDefinitionReaderbeanDefinitionReader=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 关键点:加载BeanDefinitionloadBeanDefinitions(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/beansif(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,注册BeanDefinitionparseBeanDefinitions(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);}}}
publicclassDefaultBeanDefinitionDocumentReaderimplementsBeanDefinitionDocumentReader{// 第一步 进入标签解析方法privatevoidparseDefaultElement(Elementele,BeanDefinitionParserDelegatedelegate){// import标签解析if(delegate.nodeNameEquals(ele,IMPORT_ELEMENT)){importBeanDefinitionResource(ele);}// alias标签解析elseif(delegate.nodeNameEquals(ele,ALIAS_ELEMENT)){processAliasRegistration(ele);}// TODO 重点看:bean标签解析elseif(delegate.nodeNameEquals(ele,BEAN_ELEMENT)){processBeanDefinition(ele,delegate);}// beans标签解析elseif(delegate.nodeNameEquals(ele,NESTED_BEANS_ELEMENT)){// recursedoRegisterBeanDefinitions(ele);}}// 第二步 进入bean标签解析方法protectedvoidprocessBeanDefinition(Elementele,BeanDefinitionParserDelegatedelegate){// TODO 重点:获取到BeanDefinitionHolder,内部封装了BeanDefinitionBeanDefinitionHolderbdHolder=delegate.parseBeanDefinitionElement(ele);if(bdHolder!=null){// 如果必要,装饰BeanDefinition,这里用到了装饰模式bdHolder=delegate.decorateBeanDefinitionIfRequired(ele,bdHolder);try{// Register the final decorated instance.BeanDefinitionReaderUtils.registerBeanDefinition(bdHolder,getReaderContext().getRegistry());}catch(BeanDefinitionStoreExceptionex){getReaderContext().error("Failed to register bean definition with name '"+bdHolder.getBeanName()+"'",ele,ex);}// Send registration event.getReaderContext().fireComponentRegistered(newBeanComponentDefinition(bdHolder));}}}
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均定义为:GenericBeanDefinitionAbstractBeanDefinitionbd=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方式获取namespaceUriStringnamespaceUri=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{// 加载ClassClass<?>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成员变量,标签属性名-处理类实例映射)