這一次搞懂Spring的XML解析原理說明
前言
Spring已經是我們Java Web開發必不可少的一個框架,其大大簡化了我們的開發,提高了開發者的效率。同時,其原始碼對於開發者來說也是寶藏,從中我們可以學習到非常優秀的設計思想以及優雅的命名規範,但因其體系龐大、設計複雜對於剛開始閱讀原始碼的人來說是非常困難的。所以在此之前首先你得下定決心,不管有多困難都得堅持下去;其次,最好先把設計模式掌握熟練;然後在開始閱讀原始碼時一定要多畫UML類圖和時序圖,多問自己為什麼要這麼設計?這樣設計的好處是什麼?還有沒有更好的設計?當然,暈車是難免的,但還是那句話,一定要持之以恆(PS:原始碼版本5.1.3.RELEASE)。
正文
熟悉IOC體系結構
要學習Spring原始碼,我們首先得要找准入口,那這個入口怎麼找呢?我們不妨先思考一下,在Spring專案啟動時,Spring做了哪些事情。這裡我以最原始的xml配置方式來分析,那麼在專案啟動時,首先肯定要先定位——找到xml配置檔案,定位之後肯定是載入——將我們的配置載入到記憶體,最後才是根據我們的配置例項化(本篇文章只講前兩個過程)。那麼Spring是如何定位和載入xml檔案的呢?涉及到哪些類呢?我們先來看張類圖:
該圖是IOC的體系圖,整體上你需要有一個大概的印象,可以看到所有的IOC都是有繼承關係的,這樣設計的好處就是任何一個子類IOC可以直接使用父類IOC載入的Bean,有點像JVM類載入的雙親委派機制;而紅色方框圈起來的是本篇涉及到的重要類,需要著重記憶它們的關係。
圖中最重要的兩個類是BeanFactory和ApplicationContext,這是所有IOC的父介面。其中BeanFactory提供了最基本的對bean的操作:
而ApplicationContex繼承了BeanFactory,同時還繼承了MessageSource、ResourceLoader、ApplicationEventPublisher等介面以提供國際化、資源載入、事件釋出等高階功能。我們應該想到平時Spring載入xml檔案應該是ApplicationContext的子類,從圖中我們可以看到一個叫ClassPathXmlApplicationContext的類,聯想到我們平時都會 將xml放到classPath下,所以我們直接從這個類開始就行,這就是優秀命名的好處。
探究配置載入的過程
在ClassPathXmlApplicationContext中有很多構造方法,其中有一個是傳入一個字串的(即配置檔案的相對路徑),但最終是呼叫的下面這個構造:
public ClassPathXmlApplicationContext( String[] configLocations,boolean refresh,@Nullable ApplicationContext parent) throws BeansException { super(parent); //建立解析器,解析configLocations setConfigLocations(configLocations); if (refresh) { refresh(); } }
首先呼叫父類構造器設定環境:
public AbstractApplicationContext(@Nullable ApplicationContext parent) { this(); setParent(parent); } public void setParent(@Nullable ApplicationContext parent) { this.parent = parent; if (parent != null) { Environment parentEnvironment = parent.getEnvironment(); if (parentEnvironment instanceof ConfigurableEnvironment) { getEnvironment().merge((ConfigurableEnvironment) parentEnvironment); } } }
然後解析傳入的相對路徑儲存到configLocations變數中,最後再呼叫父類AbstractApplicationContext的refresh方法重新整理容器(啟動容器都會呼叫該方法),我們著重來看這個方法:
public void refresh() throws BeansException,IllegalStateException { synchronized (this.startupShutdownMonitor) { //為容器初始化做準備 prepareRefresh(); // 解析xml 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) { 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(); } } }
這個方法是一個典型的模板方法模式的實現,第一步是準備初始化容器環境,這一步不重要,重點是第二步,建立BeanFactory物件、載入解析xml並封裝成BeanDefinition物件都是在這一步完成的。
protected ConfigurableListableBeanFactory obtainFreshBeanFactory() { refreshBeanFactory(); return getBeanFactory(); }
點進去看是呼叫了refreshBeanFactory方法,但這裡有兩個實現,應該進哪一個類裡面呢?
如果你還記得前面的繼承體系,那你就會毫不猶豫的進入AbstractRefreshableApplicationContext類中,所以在閱讀原始碼的過程中一定要記住類的繼承體系。
protected final void refreshBeanFactory() throws BeansException { //如果BeanFactory不為空,則清除BeanFactory和裡面的例項 if (hasBeanFactory()) { destroyBeans(); closeBeanFactory(); } try { //建立DefaultListableBeanFactory DefaultListableBeanFactory beanFactory = createBeanFactory(); beanFactory.setSerializationId(getId()); //設定是否可以迴圈依賴 allowCircularReferences //是否允許使用相同名稱重新註冊不同的bean實現. customizeBeanFactory(beanFactory); //解析xml,並把xml中的標籤封裝成BeanDefinition物件 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和物件例項,然後建立了一個DefaultListableBeanFactory物件並傳入到了loadBeanDefinitions方法中,這也是一個模板方法,因為我們的配置不止有xml,還有註解等,所以這裡我們應該進入AbstractXmlApplicationContext類中:
protected void loadBeanDefinitions(DefaultListableBeanFactory beanFactory) throws BeansException,IOException { //建立xml的解析器,這裡是一個委託模式 XmlBeanDefinitionReader beanDefinitionReader = new XmlBeanDefinitionReader(beanFactory); // Configure the bean definition reader with this context's // resource loading environment. beanDefinitionReader.setEnvironment(this.getEnvironment()); //這裡傳一個this進去,因為ApplicationContext是實現了ResourceLoader介面的 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. initBeanDefinitionReader(beanDefinitionReader); //主要看這個方法 loadBeanDefinitions(beanDefinitionReader); }
首先建立了一個XmlBeanDefinitionReader物件,見名知意,這個就是解析xml的類,需要注意的是該類的構造方法接收的是BeanDefinitionRegistry物件,而這裡將DefaultListableBeanFactory物件傳入了進去(別忘記了這個物件是實現了BeanDefinitionRegistry類的),如果你足夠敏感,應該可以想到後面會委託給該類去註冊。註冊什麼呢?自然是註冊BeanDefintion。記住這個猜想,我們稍後來驗證是不是這麼回事。
接著進入loadBeanDefinitions方法獲取之前儲存的xml配置檔案路徑,並委託給XmlBeanDefinitionReader物件解析載入:
protected void loadBeanDefinitions(XmlBeanDefinitionReader reader) throws BeansException,IOException { Resource[] configResources = getConfigResources(); if (configResources != null) { reader.loadBeanDefinitions(configResources); } //獲取需要載入的xml配置檔案 String[] configLocations = getConfigLocations(); if (configLocations != null) { reader.loadBeanDefinitions(configLocations); } }
最後會進入到抽象父類AbstractBeanDefinitionReader中:
public int loadBeanDefinitions(String location,@Nullable Set<Resource> actualResources) throws BeanDefinitionStoreException { // 這裡獲取到的依然是DefaultListableBeanFactory物件 ResourceLoader resourceLoader = getResourceLoader(); if (resourceLoader == null) { throw new BeanDefinitionStoreException( "Cannot load bean definitions from location [" + location + "]: no ResourceLoader available"); } if (resourceLoader instanceof ResourcePatternResolver) { // Resource pattern matching available. try { //把字串型別的xml檔案路徑,形如:classpath*:user/**/*-context.xml,轉換成Resource物件型別,其實就是用流 //的方式載入配置檔案,然後封裝成Resource物件 Resource[] resources = ((ResourcePatternResolver) resourceLoader).getResources(location); //主要看這個方法 int count = loadBeanDefinitions(resources); if (actualResources != null) { Collections.addAll(actualResources,resources); } if (logger.isTraceEnabled()) { logger.trace("Loaded " + count + " bean definitions from location pattern [" + location + "]"); } return count; } catch (IOException ex) { throw new BeanDefinitionStoreException( "Could not resolve bean definition resource pattern [" + location + "]",ex); } } else { // Can only load single resources by absolute URL. Resource resource = resourceLoader.getResource(location); int count = loadBeanDefinitions(resource); if (actualResources != null) { actualResources.add(resource); } if (logger.isTraceEnabled()) { logger.trace("Loaded " + count + " bean definitions from location [" + location + "]"); } return count; } }
這個方法中主要將xml配置載入到存中並封裝成為Resource物件,這一步不重要,可以略過,主要的還是loadBeanDefinitions方法,最終還是呼叫到子類XmlBeanDefinitionReader的方法:
public int loadBeanDefinitions(EncodedResource encodedResource) throws BeanDefinitionStoreException { try { //獲取Resource物件中的xml檔案流物件 InputStream inputStream = encodedResource.getResource().getInputStream(); try { //InputSource是jdk中的sax xml檔案解析物件 InputSource inputSource = new InputSource(inputStream); if (encodedResource.getEncoding() != null) { inputSource.setEncoding(encodedResource.getEncoding()); } //主要看這個方法 return doLoadBeanDefinitions(inputSource,encodedResource.getResource()); } finally { inputStream.close(); } } } protected int doLoadBeanDefinitions(InputSource inputSource,Resource resource) throws BeanDefinitionStoreException { try { //把inputSource 封裝成Document檔案物件,這是jdk的API Document doc = doLoadDocument(inputSource,resource); //主要看這個方法,根據解析出來的document物件,拿到裡面的標籤元素封裝成BeanDefinition int count = registerBeanDefinitions(doc,resource); if (logger.isDebugEnabled()) { logger.debug("Loaded " + count + " bean definitions from " + resource); } return count; } } public int registerBeanDefinitions(Document doc,Resource resource) throws BeanDefinitionStoreException { // 建立DefaultBeanDefinitionDocumentReader物件,並委託其做解析註冊工作 BeanDefinitionDocumentReader documentReader = createBeanDefinitionDocumentReader(); int countBefore = getRegistry().getBeanDefinitionCount(); //主要看這個方法,需要注意createReaderContext方法中建立的幾個物件 documentReader.registerBeanDefinitions(doc,createReaderContext(resource)); return getRegistry().getBeanDefinitionCount() - countBefore; } public XmlReaderContext createReaderContext(Resource resource) { // XmlReaderContext物件中儲存了XmlBeanDefinitionReader物件和DefaultNamespaceHandlerResolver物件的引用,在後面會用到 return new XmlReaderContext(resource,this.problemReporter,this.eventListener,this.sourceExtractor,this,getNamespaceHandlerResolver()); }
接著看看DefaultBeanDefinitionDocumentReader中是如何解析的:
protected void doRegisterBeanDefinitions(Element root) { // 建立了BeanDefinitionParserDelegate物件 BeanDefinitionParserDelegate parent = this.delegate; this.delegate = createDelegate(getReaderContext(),root,parent); // 如果是Spring原生名稱空間,首先解析 profile標籤,這裡不重要 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); // 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; } } } preProcessXml(root); //主要看這個方法,標籤具體解析過程 parseBeanDefinitions(root,this.delegate); postProcessXml(root); this.delegate = parent; }
在這個方法中重點關注preProcessXml、parseBeanDefinitions、postProcessXml三個方法,其中preProcessXml和postProcessXml都是空方法,意思是在解析標籤前後我們自己可以擴充套件需要執行的操作,也是一個模板方法模式,體現了Spring的高擴充套件性。然後進入parseBeanDefinitions方法看具體是怎麼解析標籤的:
protected void parseBeanDefinitions(Element root,BeanDefinitionParserDelegate delegate) { if (delegate.isDefaultNamespace(root)) { NodeList nl = root.getChildNodes(); for (int i = 0; i < nl.getLength(); i++) { Node node = nl.item(i); if (node instanceof Element) { Element ele = (Element) node; if (delegate.isDefaultNamespace(ele)) { //預設標籤解析 parseDefaultElement(ele,delegate); } else { //自定義標籤解析 delegate.parseCustomElement(ele); } } } } else { delegate.parseCustomElement(root); } }
這裡有兩種標籤的解析:Spring原生標籤和自定義標籤。怎麼區分這兩種標籤呢?
// 自定義標籤 <context:component-scan/> // 預設標籤 <bean:/>
如上,帶字首的就是自定義標籤,否則就是Spring預設標籤,無論哪種標籤在使用前都需要在Spring的xml配置檔案裡宣告Namespace URI,這樣在解析標籤時才能通過Namespace URI找到對應的NamespaceHandler。
xmlns:context="http://www.springframework.org/schema/context"
http://www.springframework.org/schema/beans
isDefaultNamespace判斷是不是預設標籤,點進去看看是不是跟我上面說的一致:
public boolean isDefaultNamespace(Node node) { return isDefaultNamespace(getNamespaceURI(node)); } public static final String BEANS_NAMESPACE_URI = "http://www.springframework.org/schema/beans"; public boolean isDefaultNamespace(@Nullable String namespaceUri) { return (!StringUtils.hasLength(namespaceUri) || BEANS_NAMESPACE_URI.equals(namespaceUri)); }
可以看到http://www.springframework.org/schema/beans所對應的就是預設標籤。接著,我們進入parseDefaultElement方法:
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標籤 else if (delegate.nodeNameEquals(ele,BEAN_ELEMENT)) { processBeanDefinition(ele,delegate); } else if (delegate.nodeNameEquals(ele,NESTED_BEANS_ELEMENT)) { // recurse doRegisterBeanDefinitions(ele); } }
這裡面主要是對import、alias、bean標籤的解析以及beans的字標籤的遞迴解析,主要看看bean標籤的解析:
protected void processBeanDefinition(Element ele,BeanDefinitionParserDelegate delegate) { // 解析elment封裝為BeanDefinitionHolder物件 BeanDefinitionHolder bdHolder = delegate.parseBeanDefinitionElement(ele); if (bdHolder != null) { // 該方法功能不重要,主要理解設計思想:裝飾者設計模式以及SPI設計思想 bdHolder = delegate.decorateBeanDefinitionIfRequired(ele,bdHolder); try { // 完成document到BeanDefinition物件轉換後,對BeanDefinition物件進行快取註冊 BeanDefinitionReaderUtils.registerBeanDefinition(bdHolder,getReaderContext().getRegistry()); } // Send registration event. getReaderContext().fireComponentRegistered(new BeanComponentDefinition(bdHolder)); } } public BeanDefinitionHolder parseBeanDefinitionElement(Element ele,@Nullable BeanDefinition containingBean) { // 獲取id和name屬性 String id = ele.getAttribute(ID_ATTRIBUTE); String nameAttr = ele.getAttribute(NAME_ATTRIBUTE); // 獲取別名屬性,多個別名可用,;隔開 List<String> aliases = new ArrayList<>(); if (StringUtils.hasLength(nameAttr)) { String[] nameArr = StringUtils.tokenizeToStringArray(nameAttr,MULTI_VALUE_ATTRIBUTE_DELIMITERS); aliases.addAll(Arrays.asList(nameArr)); } String beanName = id; if (!StringUtils.hasText(beanName) && !aliases.isEmpty()) { beanName = aliases.remove(0); if (logger.isTraceEnabled()) { logger.trace("No XML 'id' specified - using '" + beanName + "' as bean name and " + aliases + " as aliases"); } } //檢查beanName是否重複 if (containingBean == null) { checkNameUniqueness(beanName,aliases,ele); } // 具體的解析封裝過程還在這個方法裡 AbstractBeanDefinition beanDefinition = parseBeanDefinitionElement(ele,beanName,containingBean); if (beanDefinition != null) { if (!StringUtils.hasText(beanName)) { try { if (containingBean != null) { beanName = BeanDefinitionReaderUtils.generateBeanName( beanDefinition,this.readerContext.getRegistry(),true); } else { beanName = this.readerContext.generateBeanName(beanDefinition); // Register an alias for the plain bean class name,if still possible,// if the generator returned the class name plus a suffix. // This is expected for Spring 1.2/2.0 backwards compatibility. String beanClassName = beanDefinition.getBeanClassName(); if (beanClassName != null && beanName.startsWith(beanClassName) && beanName.length() > beanClassName.length() && !this.readerContext.getRegistry().isBeanNameInUse(beanClassName)) { aliases.add(beanClassName); } } if (logger.isTraceEnabled()) { logger.trace("Neither XML 'id' nor 'name' specified - " + "using generated bean name [" + beanName + "]"); } } catch (Exception ex) { error(ex.getMessage(),ele); return null; } } String[] aliasesArray = StringUtils.toStringArray(aliases); return new BeanDefinitionHolder(beanDefinition,aliasesArray); } return null; } // bean的解析 public AbstractBeanDefinition parseBeanDefinitionElement( Element ele,String beanName,@Nullable BeanDefinition containingBean) { this.parseState.push(new BeanEntry(beanName)); // 獲取class名稱和父類名稱 String className = null; if (ele.hasAttribute(CLASS_ATTRIBUTE)) { className = ele.getAttribute(CLASS_ATTRIBUTE).trim(); } String parent = null; if (ele.hasAttribute(PARENT_ATTRIBUTE)) { parent = ele.getAttribute(PARENT_ATTRIBUTE); } try { // 建立GenericBeanDefinition物件 AbstractBeanDefinition bd = createBeanDefinition(className,parent); // 解析bean標籤的屬性,並把解析出來的屬性設定到BeanDefinition物件中 parseBeanDefinitionAttributes(ele,containingBean,bd); bd.setDescription(DomUtils.getChildElementValueByTagName(ele,DESCRIPTION_ELEMENT)); //解析bean中的meta標籤 parseMetaElements(ele,bd); //解析bean中的lookup-method標籤 parseLookupOverrideSubElements(ele,bd.getMethodOverrides()); //解析bean中的replaced-method標籤 parseReplacedMethodSubElements(ele,bd.getMethodOverrides()); //解析bean中的constructor-arg標籤 parseConstructorArgElements(ele,bd); //解析bean中的property標籤 parsePropertyElements(ele,bd); parseQualifierElements(ele,bd); bd.setResource(this.readerContext.getResource()); bd.setSource(extractSource(ele)); return bd; } return null; }
bean標籤的解析步驟仔細理解並不複雜,就是將一個個標籤屬性的值裝入到了BeanDefinition物件中,這裡需要注意parseConstructorArgElements和parsePropertyElements方法,分別是對constructor-arg和property標籤的解析,解析完成後分別裝入了BeanDefinition物件的constructorArgumentValues和propertyValues中,而這兩個屬性在接下來c和p標籤的解析中還會用到,而且還涉及一個很重要的設計思想——裝飾器模式。
Bean標籤解析完成後將生成的BeanDefinition物件、bean的名稱以及別名一起封裝到了BeanDefinitionHolder物件並返回,然後呼叫了decorateBeanDefinitionIfRequired進行裝飾:
public BeanDefinitionHolder decorateBeanDefinitionIfRequired( Element ele,BeanDefinitionHolder definitionHolder,@Nullable BeanDefinition containingBd) { BeanDefinitionHolder finalDefinition = definitionHolder; //根據bean標籤屬性裝飾BeanDefinitionHolder,比如<bean class="xx" p:username="dark"/> NamedNodeMap attributes = ele.getAttributes(); for (int i = 0; i < attributes.getLength(); i++) { Node node = attributes.item(i); finalDefinition = decorateIfRequired(node,finalDefinition,containingBd); } //根據bean標籤子元素裝飾BeanDefinitionHolder\ NodeList children = ele.getChildNodes(); for (int i = 0; i < children.getLength(); i++) { Node node = children.item(i); if (node.getNodeType() == Node.ELEMENT_NODE) { finalDefinition = decorateIfRequired(node,containingBd); } } return finalDefinition; }
在這個方法中分別對Bean標籤的屬性和子標籤迭代,獲取其中的自定義標籤進行解析,並裝飾之前建立的BeanDefinition物件,如同下面的c和p:
// c:和p:表示通過構造器和屬性的setter方法給屬性賦值,是constructor-arg和property的簡化寫法
<bean class="com.dark.bean.Student" id="student" p:username="Dark" p:password="111" c:age="12" c:sex="1"/>
兩個步驟是一樣的,我們點進decorateIfRequired方法中:
public BeanDefinitionHolder decorateIfRequired( Node node,BeanDefinitionHolder originalDef,@Nullable BeanDefinition containingBd) { //根據node獲取到node的名稱空間,形如:http://www.springframework.org/schema/p String namespaceUri = getNamespaceURI(node); if (namespaceUri != null && !isDefaultNamespace(namespaceUri)) { // 根據配置檔案獲取namespaceUri對應的處理類,SPI思想 NamespaceHandler handler = this.readerContext.getNamespaceHandlerResolver().resolve(namespaceUri); if (handler != null) { //呼叫NamespaceHandler處理類的decorate方法,開始具體裝飾過程,並返回裝飾完的物件 BeanDefinitionHolder decorated = handler.decorate(node,originalDef,new ParserContext(this.readerContext,containingBd)); if (decorated != null) { return decorated; } } else if (namespaceUri.startsWith("http://www.springframework.org/")) { error("Unable to locate Spring NamespaceHandler for XML schema namespace [" + namespaceUri + "]",node); } else { // A custom namespace,not to be handled by Spring - maybe "xml:...". if (logger.isDebugEnabled()) { logger.debug("No Spring NamespaceHandler found for XML schema namespace [" + namespaceUri + "]"); } } } return originalDef; }
這裡也和我們之前說的一樣,首先獲取到標籤對應的namespaceUri,然後通過這個Uri去獲取到對應的NamespceHandler,最後再呼叫NamespceHandler的decorate方法進行裝飾。我們先來看看獲取NamespceHandler的過程,這涉及到一個非常重要的高擴充套件性的思想——SPI(有關SPI,在我之前的文章Dubbo——SPI及自適應擴充套件原理中已經詳細講解過,這裡不再贅述):
public NamespaceHandler resolve(String namespaceUri) { // 獲取spring中所有jar包裡面的 "META-INF/spring.handlers"檔案,並且建立對映關係 Map<String,Object> handlerMappings = getHandlerMappings(); //根據namespaceUri:http://www.springframework.org/schema/p,獲取到這個名稱空間的處理類 Object handlerOrClassName = handlerMappings.get(namespaceUri); if (handlerOrClassName == null) { return null; } else if (handlerOrClassName instanceof NamespaceHandler) { return (NamespaceHandler) handlerOrClassName; } else { String className = (String) handlerOrClassName; try { Class<?> handlerClass = ClassUtils.forName(className,this.classLoader); if (!NamespaceHandler.class.isAssignableFrom(handlerClass)) { throw new FatalBeanException("Class [" + className + "] for namespace [" + namespaceUri + "] does not implement the [" + NamespaceHandler.class.getName() + "] interface"); } NamespaceHandler namespaceHandler = (NamespaceHandler) BeanUtils.instantiateClass(handlerClass); //呼叫處理類的init方法,在init方法中完成標籤元素解析類的註冊 namespaceHandler.init(); handlerMappings.put(namespaceUri,namespaceHandler); return namespaceHandler; } } } // AOP標籤對應的NamespaceHandler,可以發現NamespaceHandler的作用就是管理和註冊與自己相關的標籤解析器 public void init() { // In 2.0 XSD as well as in 2.1 XSD. registerBeanDefinitionParser("config",new ConfigBeanDefinitionParser()); registerBeanDefinitionParser("aspectj-autoproxy",new AspectJAutoProxyBeanDefinitionParser()); registerBeanDefinitionDecorator("scoped-proxy",new ScopedProxyBeanDefinitionDecorator()); // Only in 2.0 XSD: moved to context namespace as of 2.1 registerBeanDefinitionParser("spring-configured",new SpringConfiguredBeanDefinitionParser()); }
看到這裡我們應該就清楚了Spring是如何解析xml裡的標籤了以及我們如果要擴充套件自己的標籤該怎麼做。只需要建立一個我們的自定義標籤和解析類,並指定它的名稱空間以及NamespaceHandler,最後在META-INF/spring.handlers檔案中指定名稱空間和NamespaceHandler的對映關係即可,就像Spring的c和p標籤一樣:
http\://www.springframework.org/schema/c=org.springframework.beans.factory.xml.SimpleConstructorNamespaceHandler
http\://www.springframework.org/schema/p=org.springframework.beans.factory.xml.SimplePropertyNamespaceHandler
像這樣使用SPI的思想設計我們的專案的話,當需要擴充套件時,不需要改動任何的程式碼,非常的方便優雅。
接著,我們回到handler的decorate方法,這裡有三個預設的實現類:NamespaceHandlerSupport、SimpleConstructorNamespaceHandler、SimplePropertyNamespaceHandler。第一個是一個抽象類,與我們這裡的流程無關,感興趣的可自行了解,第二個和第三個則分別是c和p標籤對應的NamespaceHandler,兩個裝飾的處理邏輯基本上是一樣的,我這裡進入的是SimpleConstructorNamespaceHandler類:
public BeanDefinitionHolder decorate(Node node,BeanDefinitionHolder definition,ParserContext parserContext) { if (node instanceof Attr) { Attr attr = (Attr) node; String argName = StringUtils.trimWhitespace(parserContext.getDelegate().getLocalName(attr)); String argValue = StringUtils.trimWhitespace(attr.getValue()); ConstructorArgumentValues cvs = definition.getBeanDefinition().getConstructorArgumentValues(); boolean ref = false; // handle -ref arguments if (argName.endsWith(REF_SUFFIX)) { ref = true; argName = argName.substring(0,argName.length() - REF_SUFFIX.length()); } ValueHolder valueHolder = new ValueHolder(ref ? new RuntimeBeanReference(argValue) : argValue); valueHolder.setSource(parserContext.getReaderContext().extractSource(attr)); // handle "escaped"/"_" arguments if (argName.startsWith(DELIMITER_PREFIX)) { String arg = argName.substring(1).trim(); // fast default check if (!StringUtils.hasText(arg)) { cvs.addGenericArgumentValue(valueHolder); } // assume an index otherwise else { int index = -1; try { index = Integer.parseInt(arg); } catch (NumberFormatException ex) { parserContext.getReaderContext().error( "Constructor argument '" + argName + "' specifies an invalid integer",attr); } if (index < 0) { parserContext.getReaderContext().error( "Constructor argument '" + argName + "' specifies a negative index",attr); } if (cvs.hasIndexedArgumentValue(index)) { parserContext.getReaderContext().error( "Constructor argument '" + argName + "' with index "+ index+" already defined using <constructor-arg>." + " Only one approach may be used per argument.",attr); } cvs.addIndexedArgumentValue(index,valueHolder); } } // no escaping -> ctr name else { String name = Conventions.attributeNameToPropertyName(argName); if (containsArgWithName(name,cvs)) { parserContext.getReaderContext().error( "Constructor argument '" + argName + "' already defined using <constructor-arg>." + " Only one approach may be used per argument.",attr); } valueHolder.setName(Conventions.attributeNameToPropertyName(argName)); cvs.addGenericArgumentValue(valueHolder); } } return definition; }
很簡單,拿到c標籤對應的值,封裝成ValueHolder,再新增到BeanDefinition的ConstructorArgumentValues屬性中去,這樣就裝飾完成了。
講到這裡你可能會覺得,這和平時看到裝飾器模式不太一樣。其實,設計模式真正想要表達的是各種模式所代表的思想,而不是死搬硬套的實現,只有靈活的運用其思想才算是真正的掌握了設計模式,而裝飾器模式的精髓就是動態的將屬性、功能、責任附加到物件上,這樣你再看這裡是否是運用了裝飾器的思想呢?
裝飾完成後返回BeanDefinitionHolder物件並呼叫BeanDefinitionReaderUtils.registerBeanDefinition方法將該物件快取起來,等待容器去例項化。這裡就是將其快取到DefaultListableBeanFactory的beanDefinitionMap屬性中,自己看看程式碼也就明白了,我就不貼程式碼了。至此,Spring的XML解析原理分析完畢,下面是我畫的時序圖,可以對照看看:
總結
本篇是Spring原始碼分析的第一篇,只是分析了refresh中的obtainFreshBeanFactory方法,我們可以看到僅僅是對XML的解析和bean定義的註冊快取,Spring就做了這麼多事,並考慮到了各個可能會擴充套件的地方,那我們平時做的專案呢?看似簡單的背後是否有深入思考過呢?
以上這篇這一次搞懂Spring的XML解析原理說明就是小編分享給大家的全部內容了,希望能給大家一個參考,也希望大家多多支援我們。