日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

【spring源码分析】IOC容器初始化(二)

發布時間:2024/4/17 编程问答 27 豆豆
生活随笔 收集整理的這篇文章主要介紹了 【spring源码分析】IOC容器初始化(二) 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

前言:在【spring源碼分析】IOC容器初始化(一)文末中已經提出loadBeanDefinitions(DefaultListableBeanFactory)的重要性,本文將以此為切入點繼續分析。


AbstractXmlApplicationContext#loadBeanDefinitions(DefaultListableBeanFactory)

1 protected void loadBeanDefinitions(DefaultListableBeanFactory beanFactory) throws BeansException, IOException { 2 // Create a new XmlBeanDefinitionReader for the given BeanFactory. 3 // 創建XmlBeanDefinitionReader對象 4 XmlBeanDefinitionReader beanDefinitionReader = new XmlBeanDefinitionReader(beanFactory); 5 6 // Configure the bean definition reader with this context's 7 // resource loading environment. 8 // 對XmlBeanDefinitionReader進行環境變量的設置 9 beanDefinitionReader.setEnvironment(this.getEnvironment()); 10 beanDefinitionReader.setResourceLoader(this); 11 beanDefinitionReader.setEntityResolver(new ResourceEntityResolver(this)); 12 13 // Allow a subclass to provide custom initialization of the reader, 14 // then proceed with actually loading the bean definitions. 15 // 對XmlBeanDefinitionReader進行設置,可以進行覆蓋 16 initBeanDefinitionReader(beanDefinitionReader); 17 // 從Resource中加載BeanDefinition 18 loadBeanDefinitions(beanDefinitionReader); 19 }

分析:

  • 首先創建一個XmlBeanDefinitionReader對象,因為我們需要解析xml文件,然后將其封裝成BeanDefinition。
  • 設置XmlBeanDefinitionReader對象的相關屬性,這里著重關注ResourceLoader,這里引申出Resource/ResourceLoader體系。
  • 從Resource中加載BeanDefinition。

Resource體系

Resource繼承InputStreamSource,為spring框架所有資源的訪問提供抽象接口,子類AbstractResource提供Resource接口的默認實現。

ResourceLoader體系

ResourceLoader為spring資源加載的統一抽象,主要應用于根據給定的資源文件地址返回相應的Resource對象,其具體的實現由相應子類去負責。

這里列出筆者認為的幾個比較重要ResourceLoader的實現類。

  • DefaultResourceLoader是ResourceLoader的默認實現
  • PathMatchingResourcePatternResolver,該類比較常用,除了支持"classpath*:"格式,還支持Ant風格的路徑匹配模式

接下來進入AbstractXmlApplicationContext#loadBeanDefinitions方法

1 protected void loadBeanDefinitions(XmlBeanDefinitionReader reader) throws BeansException, IOException { 2 // 從配置文件Resource中,加載BeanDefinition 3 Resource[] configResources = getConfigResources(); 4 if (configResources != null) { 5 reader.loadBeanDefinitions(configResources); 6 } 7 // 從配置文件地址中,加載BeanDefinition 8 String[] configLocations = getConfigLocations(); 9 if (configLocations != null) { 10 reader.loadBeanDefinitions(configLocations); 11 } 12 }

分析:

看到這里是否很熟悉因為我們在【spring源碼分析】IOC容器初始化(一)中已經設置了資源文件的路徑(setConfigLocations)方法,因此這里會直接走到第9行處,然后調用AbstractBeanDefinitionReader#loadBeanDefinitions方法:

1 public int loadBeanDefinitions(String... locations) throws BeanDefinitionStoreException { 2 Assert.notNull(locations, "Location array must not be null"); 3 int count = 0; 4 for (String location : locations) { 5 count += loadBeanDefinitions(location); 6 } 7 return count; 8 }

分析:

這里會遍歷locations,并返回最終加載bean的個數,函數最終切入點:AbstractBeanDefinitionReader#loadBeanDefinitions(String location, @Nullable Set<Resource> actualResources):

1 public int loadBeanDefinitions(String location, @Nullable Set<Resource> actualResources) throws BeanDefinitionStoreException { 2 // 獲取ResourceLoader對象 3 ResourceLoader resourceLoader = getResourceLoader(); 4 // 資源加載器為null,拋出異常 5 if (resourceLoader == null) { 6 throw new BeanDefinitionStoreException( 7 "Cannot load bean definitions from location [" + location + "]: no ResourceLoader available"); 8 } 9 10 // 如果當前ResourceLoader為匹配模式形式的[支持一個location返回Resource[]數組形式] 11 if (resourceLoader instanceof ResourcePatternResolver) { 12 // Resource pattern matching available. 13 try { 14 // 通過location返回Resource[]數組,通過匹配模式形式,可能存在多個Resource 15 Resource[] resources = ((ResourcePatternResolver) resourceLoader).getResources(location); 16 // 加載BeanDefinition,返回BeanDefinition加載的個數 17 int count = loadBeanDefinitions(resources); 18 // 將Resource[] 添加到actualResources中 19 if (actualResources != null) { 20 Collections.addAll(actualResources, resources); 21 } 22 if (logger.isTraceEnabled()) { 23 logger.trace("Loaded " + count + " bean definitions from location pattern [" + location + "]"); 24 } 25 // 返回BeanDefinition加載的個數 26 return count; 27 } catch (IOException ex) { 28 throw new BeanDefinitionStoreException( 29 "Could not resolve bean definition resource pattern [" + location + "]", ex); 30 } 31 // ResourceLoader為默認資源加載器,一個location返回一個Resource 32 } else { 33 // Can only load single resources by absolute URL. 34 Resource resource = resourceLoader.getResource(location); 35 // 加載BeanDefinition,并返回加載BeanDefinition的個數 36 int count = loadBeanDefinitions(resource); 37 // 將Resource添加到actualResources中 38 if (actualResources != null) { 39 actualResources.add(resource); 40 } 41 if (logger.isTraceEnabled()) { 42 logger.trace("Loaded " + count + " bean definitions from location [" + location + "]"); 43 } 44 // 返回BeanDefinition加載的個數 45 return count; 46 } 47 }

分析:

  • 首先獲取ResourceLoader,ResourceLoader的賦值在創建XmlBeanDefinitionReader的過程中,如果未指定則會創建一個PathMatchingResourcePatternResolver對象。
  • 然后根據對應的ResourceLoader返回的Resource對象。

關注第15行代碼,getResources(String)方法,這里會直接委托給PathMatchingResourcePatternResolver#getResources(String)進行處理:

1 public Resource[] getResources(String locationPattern) throws IOException { 2 Assert.notNull(locationPattern, "Location pattern must not be null"); 3 4 // 以"classpath*:"開頭的location 5 if (locationPattern.startsWith(CLASSPATH_ALL_URL_PREFIX)) { 6 // a class path resource (multiple resources for same name possible) 7 8 // #1.isPattern函數的入參為路徑 9 // #2.所以這里判斷路徑是否包含通配符 如com.develop.resource.* 10 if (getPathMatcher().isPattern(locationPattern.substring(CLASSPATH_ALL_URL_PREFIX.length()))) { 11 // a class path resource pattern 12 // 這里通過通配符返回Resource[] 13 return findPathMatchingResources(locationPattern); 14 // 路徑不包含通配符 15 } else { 16 // all class path resources with the given name 17 // 通過給定的路徑,找到所有匹配的資源 18 return findAllClassPathResources(locationPattern.substring(CLASSPATH_ALL_URL_PREFIX.length())); 19 } 20 // 不以"classpath*:" 21 } else { 22 // Generally only look for a pattern after a prefix here, 23 // and on Tomcat only after the "*/" separator for its "war:" protocol. 24 // 通常在這里只是通過前綴后面進行查找,并且在tomcat中只有在"*/"分隔符之后才是其"war:"協議 25 // #1.如果是以"war:"開頭,定位其前綴位置 26 // #2.如果不是以"war:"開頭,則prefixEnd=0 27 int prefixEnd = (locationPattern.startsWith("war:") ? locationPattern.indexOf("*/") + 1 : 28 locationPattern.indexOf(':') + 1); 29 // 判斷路徑中是否含有通配符否含有通配符 30 if (getPathMatcher().isPattern(locationPattern.substring(prefixEnd))) { 31 // a file pattern 32 // 通過通配符返回返回Resource[] 33 return findPathMatchingResources(locationPattern); 34 // 路徑不包含通配符 35 } else { 36 // a single resource with the given name 37 // 通過給定的location返回一個Resource,封裝成數組形式 38 // 獲取Resource的過程都是通過委托給相應的ResourceLoader實現 39 return new Resource[]{getResourceLoader().getResource(locationPattern)}; 40 } 41 } 42 }

分析:

首先兩大分支:根據資源路徑是否包含"classpath*:"進行處理。

#1."classpath*:"分支:

  • 首先判斷路徑中是否含有通配符"*"或"?",然后執行findPathMatchingResources函數。
  • 如果不包含通配符,則根據路徑找到所有匹配的資源,執行findAllClassPathResources函數。

#2.路徑中不含"classpath*:"分支,與上述過程一樣,同樣按分支含有通配符與不含通配符進行處理。

PathMatchingResourcePatternResolver#findPathMatchingResources(String)

1 protected Resource[] findPathMatchingResources(String locationPattern) throws IOException { 2 // 確定根路徑與子路徑 3 String rootDirPath = determineRootDir(locationPattern); 4 String subPattern = locationPattern.substring(rootDirPath.length()); 5 // 得到根路徑下的資源 6 Resource[] rootDirResources = getResources(rootDirPath); 7 Set<Resource> result = new LinkedHashSet<>(16); 8 // 遍歷獲取資源 9 for (Resource rootDirResource : rootDirResources) { 10 // 解析根路徑資源 11 rootDirResource = resolveRootDirResource(rootDirResource); 12 URL rootDirUrl = rootDirResource.getURL(); 13 // bundle類型資源 14 if (equinoxResolveMethod != null && rootDirUrl.getProtocol().startsWith("bundle")) { 15 URL resolvedUrl = (URL) ReflectionUtils.invokeMethod(equinoxResolveMethod, null, rootDirUrl); 16 if (resolvedUrl != null) { 17 rootDirUrl = resolvedUrl; 18 } 19 rootDirResource = new UrlResource(rootDirUrl); 20 } 21 // vfs類型資源 22 if (rootDirUrl.getProtocol().startsWith(ResourceUtils.URL_PROTOCOL_VFS)) { 23 result.addAll(VfsResourceMatchingDelegate.findMatchingResources(rootDirUrl, subPattern, getPathMatcher())); 24 // jar類型資源 25 } else if (ResourceUtils.isJarURL(rootDirUrl) || isJarResource(rootDirResource)) { 26 result.addAll(doFindPathMatchingJarResources(rootDirResource, rootDirUrl, subPattern)); 27 // 其他類型資源 28 } else { 29 result.addAll(doFindPathMatchingFileResources(rootDirResource, subPattern)); 30 } 31 } 32 if (logger.isDebugEnabled()) { 33 logger.debug("Resolved location pattern [" + locationPattern + "] to resources " + result); 34 } 35 // 將結果封裝成數組形式 注意該轉換形式 36 return result.toArray(new Resource[0]); 37 }

分析:

函數的整體處理邏輯比較簡單,根據不同的資源類型,將資源最終轉換為Resource數組。

特別分析:

determineRootDir(String)

1 protected String determineRootDir(String location) { 2 // 確定":"的后一位,如果":"不存在,則prefixEnd=0 3 int prefixEnd = location.indexOf(':') + 1; 4 // location的長度 5 int rootDirEnd = location.length(); 6 // 從location的":"開始(可能不存在)一直到location結束,判斷是否包含通配符,如果存在,則截取最后一個"/"分割的部分 7 /** 8 * 截取過程: 9 * classpath*:com/dev/config/* 10 * prefixEnd=11 11 * subString(prefixEnd,rootDirEnd)=com/dev/config/* 12 * 第一次循環rootDirEnd=26,也就是最后一個"/" 13 * subString(prefixEnd,rootDirEnd)=com/dev/config/ 14 * 第二次循環已經不包含通配符了,跳出循環 15 * 所以根路徑為classpath*:com/dev/config/ 16 */ 17 while (rootDirEnd > prefixEnd && getPathMatcher().isPattern(location.substring(prefixEnd, rootDirEnd))) { 18 // 確定最后一個"/"位置的后一位,注意這里rootDirEnd-2是為了縮小搜索范圍,提升速度 19 rootDirEnd = location.lastIndexOf('/', rootDirEnd - 2) + 1; 20 } 21 // 如果查找完后rootDirEnd=0,則將prefixEnd賦值給rootDirEnd,也就是冒號的后一位 22 if (rootDirEnd == 0) { 23 rootDirEnd = prefixEnd; 24 } 25 // 截取根目錄 26 return location.substring(0, rootDirEnd); 27 }

分析:

該函數有點繞,整體思想就是決定出給定資源路徑的根路徑,代碼中已經給出了詳細注釋,處理效果如下實例:

PathMatchingResourcePatternResolver#findAllClassPathResources(String)

1 protected Resource[] findAllClassPathResources(String location) throws IOException { 2 String path = location; 3 // location是否已"/"開頭 4 if (path.startsWith("/")) { 5 path = path.substring(1); 6 } 7 // 真正加載location下所有classpath下的資源 8 Set<Resource> result = doFindAllClassPathResources(path); 9 if (logger.isDebugEnabled()) { 10 logger.debug("Resolved classpath location [" + location + "] to resources " + result); 11 } 12 return result.toArray(new Resource[0]); 13 }

分析:

該函數會查找路徑下的所有資源,核心函數doFindAllClassPathResources(String):

1 protected Set<Resource> doFindAllClassPathResources(String path) throws IOException { 2 Set<Resource> result = new LinkedHashSet<>(16); 3 ClassLoader cl = getClassLoader(); 4 // 根據ClassLoader來加載資源 5 // 如果PathMatchingResourcePatternResolver在初始化時,設置了ClassLoader,就用該ClassLoader的getResouce方法 6 // 否則調用ClassLoader的getSystemResource方法 7 Enumeration<URL> resourceUrls = (cl != null ? cl.getResources(path) : ClassLoader.getSystemResources(path)); 8 // 遍歷集合將集合轉換成UrlResource形式 9 // 如果path為空,這里就會返回項目中classes的路徑,通過addAllClassLoaderJarRoots方法進行加載 10 while (resourceUrls.hasMoreElements()) { 11 URL url = resourceUrls.nextElement(); 12 result.add(convertClassLoaderURL(url)); 13 } 14 // 如果path為空,則加載路徑下的所有jar 15 if ("".equals(path)) { 16 // The above result is likely to be incomplete, i.e. only containing file system references. 17 // We need to have pointers to each of the jar files on the classpath as well... 18 // 加載所有jar 19 addAllClassLoaderJarRoots(cl, result); 20 } 21 return result; 22 }

分析:該函數的主要功能就是將搜索配置文件路徑下的所有資源,然后封裝成Resource集合返回,供加載BeanDefinition使用。

不含"classpath*:"分支的邏輯與上述分析差不多,這里不再做過多贅述。

Resource資源準備就緒后,再次回到loadBeanDefinitions(String location, @Nullable Set<Resource> actualResources)函數中,在第17行代碼處進入正式加載BeanDefinition過程。

AbstractBeanDefinitionReader#loadBeanDefinitions(Resource... resources)

1 public int loadBeanDefinitions(Resource... resources) throws BeanDefinitionStoreException { 2 Assert.notNull(resources, "Resource array must not be null"); 3 int count = 0; 4 // 通過循環的形式單個加載BeanDefinition 5 for (Resource resource : resources) { 6 count += loadBeanDefinitions(resource); 7 } 8 return count; 9 }

在循環過程中會落入XmlBeanDefinitionReader#loadBeanDefinitions(Resource resource)

1 public int loadBeanDefinitions(Resource resource) throws BeanDefinitionStoreException { 2 // 這里會將Resource封裝成EncodeResource,主要主要為了內容讀取的正確性 3 return loadBeanDefinitions(new EncodedResource(resource)); 4 }

該函數將Resource封裝成EncodeResource,主要是為了內容讀取的正確性,然后進入加載BeanDefinition的核心函數XmlBeanDefinitionReader#loadBeanDefinitions(EncodedResource encodedResource)

1 public int loadBeanDefinitions(EncodedResource encodedResource) throws BeanDefinitionStoreException { 2 Assert.notNull(encodedResource, "EncodedResource must not be null"); 3 if (logger.isInfoEnabled()) { 4 logger.info("Loading XML bean definitions from " + encodedResource.getResource()); 5 } 6 7 // 獲取已經加載過的資源 8 Set<EncodedResource> currentResources = this.resourcesCurrentlyBeingLoaded.get(); 9 // 表示當前沒有資源加載 10 if (currentResources == null) { 11 currentResources = new HashSet<>(4); 12 this.resourcesCurrentlyBeingLoaded.set(currentResources); 13 } 14 // 將當前資源加入記錄中,如果已經存在,則拋出異常,因為currentResource為Set集合 15 // 這里主要為了避免一個EncodeResource還沒加載完成時,又加載本身,造成死循環(Detected cyclic loading of) 16 if (!currentResources.add(encodedResource)) { 17 throw new BeanDefinitionStoreException( 18 "Detected cyclic loading of " + encodedResource + " - check your import definitions!"); 19 } 20 try { 21 // 從封裝的encodeResource中獲取resource,并取得其輸入流,通過流對資源進行操作 22 InputStream inputStream = encodedResource.getResource().getInputStream(); 23 try { 24 // 將流封裝成InputSource 25 InputSource inputSource = new InputSource(inputStream); 26 // 設置InputSource的編碼 27 if (encodedResource.getEncoding() != null) { 28 inputSource.setEncoding(encodedResource.getEncoding()); 29 } 30 // 核心邏輯,實現BeanDefinition的加載 31 return doLoadBeanDefinitions(inputSource, encodedResource.getResource()); 32 } finally { 33 inputStream.close(); 34 } 35 } catch (IOException ex) { 36 throw new BeanDefinitionStoreException( 37 "IOException parsing XML document from " + encodedResource.getResource(), ex); 38 } finally { 39 // 最后從緩存中清除資源 40 currentResources.remove(encodedResource); 41 // 如果當前資源集合為空,則從EncodeResource集合中移除當前資源的集合 42 if (currentResources.isEmpty()) { 43 this.resourcesCurrentlyBeingLoaded.remove(); 44 } 45 } 46 }

分析:

  • 首先判斷緩存中是否已經存在當前資源,如果存在則拋出異常,這里是為了避免循環加載。
  • 然后取出文件流封裝成InputSource,進入加載BeanDefinition的核心函數doLoadBeanDefinitions。
1 protected int doLoadBeanDefinitions(InputSource inputSource, Resource resource) 2 throws BeanDefinitionStoreException { 3 try { 4 // #1.獲取XML的Document實例 5 Document doc = doLoadDocument(inputSource, resource); 6 // #2.根據Document注冊bean,并返回注冊的bean的個數 7 return registerBeanDefinitions(doc, resource); 8 } catch (BeanDefinitionStoreException ex) { 9 throw ex; 10 } catch (SAXParseException ex) { 11 throw new XmlBeanDefinitionStoreException(resource.getDescription(), 12 "Line " + ex.getLineNumber() + " in XML document from " + resource + " is invalid", ex); 13 } catch (SAXException ex) { 14 throw new XmlBeanDefinitionStoreException(resource.getDescription(), 15 "XML document from " + resource + " is invalid", ex); 16 } catch (ParserConfigurationException ex) { 17 throw new BeanDefinitionStoreException(resource.getDescription(), 18 "Parser configuration exception parsing XML from " + resource, ex); 19 } catch (IOException ex) { 20 throw new BeanDefinitionStoreException(resource.getDescription(), 21 "IOException parsing XML document from " + resource, ex); 22 } catch (Throwable ex) { 23 throw new BeanDefinitionStoreException(resource.getDescription(), 24 "Unexpected exception parsing XML document from " + resource, ex); 25 } 26 }

分析:

  • 首先獲取XML配置文件的Document實例。
  • 根據Document注冊Bean,并返回注冊Bean的個數。

XmlBeanDefinitionReader#doLoadDocument(InputSource inputSource, Resource resource)

protected Document doLoadDocument(InputSource inputSource, Resource resource) throws Exception {return this.documentLoader.loadDocument(inputSource, getEntityResolver(), this.errorHandler,getValidationModeForResource(resource), isNamespaceAware());}

分析:

這里是委派給DefaultDocumentLoader#loadDocument函數來實現。

這里有一個驗證模式的入參,從getValidationModeForResource函數而來:

1 protected int getValidationModeForResource(Resource resource) { 2 // 獲取指定的驗證模式,默認為自動模式 3 int validationModeToUse = getValidationMode(); 4 // #1.如果驗證模式不為自動驗證模式,則表示進行了設置,則直接返回驗證模式即可 5 if (validationModeToUse != VALIDATION_AUTO) { 6 return validationModeToUse; 7 } 8 // #2.到這里表示使用了自動驗證模式,再次檢測Resource使用的驗證模式 9 int detectedMode = detectValidationMode(resource); 10 if (detectedMode != VALIDATION_AUTO) { 11 return detectedMode; 12 } 13 // 最后使用默認的VALIDATION_XSD驗證模式 14 // Hmm, we didn't get a clear indication... Let's assume XSD, 15 // since apparently no DTD declaration has been found up until 16 // detection stopped (before finding the document's root tag). 17 return VALIDATION_XSD; 18 }

分析:

  • 首先獲取當前的驗證模式,默認為自動驗證模式。
  • 如果當前驗證模式不為自動驗證模式,則表示進行了設置,則直接返回當前驗證模式即可。
  • 如果使用了自動驗證模式,則需再次檢測Resource使用的驗證模式
  • 最后,如果還是自動驗證模式,則返回XSD驗證模式。

這里要科普一下DTD與XSD

DTD(Document Type Definition),即文檔類型定義,為 XML 文件的驗證機制,屬于 XML 文件中組成的一部分。DTD 是一種保證 XML 文檔格式正確的有效驗證方式,它定義了相關 XML 文檔的元素、屬性、排列方式、元素的內容類型以及元素的層次結構。其實 DTD 就相當于 XML 中的 “詞匯”和“語法”,我們可以通過比較 XML 文件和 DTD 文件 來看文檔是否符合規范,元素和標簽使用是否正確。

但是DTD存在著一些缺陷:

  • 它沒有使用 XML 格式,而是自己定義了一套格式,相對解析器的重用性較差;而且 DTD 的構建和訪問沒有標準的編程接口,因而解析器很難簡單的解析 DTD 文檔。
  • DTD 對元素的類型限制較少;同時其他的約束力也叫弱。
  • DTD 擴展能力較差。
  • 基于正則表達式的 DTD 文檔的描述能力有限。

針對 DTD 的缺陷,W3C 在 2001 年推出 XSD。XSD(XML Schemas Definition)即 XML Schema 語言。XML Schema 本身就是一個 XML文檔,使用的是 XML 語法,因此可以很方便的解析 XSD 文檔。相對于 DTD,XSD 具有如下優勢:

  • XML Schema 基于 XML ,沒有專門的語法。
  • XML Schema 可以象其他 XML 文件一樣解析和處理。
  • XML Schema 比 DTD 提供了更豐富的數據類型。
  • XML Schema 提供可擴充的數據模型。
  • XML Schema 支持綜合命名空間。
  • XML Schema 支持屬性組。

spring中定義了一些驗證模式:

/*** Indicates that the validation should be disabled. 禁用驗證模式*/public static final int VALIDATION_NONE = XmlValidationModeDetector.VALIDATION_NONE;/*** Indicates that the validation mode should be detected automatically. 自動獲取驗證模式*/public static final int VALIDATION_AUTO = XmlValidationModeDetector.VALIDATION_AUTO;/*** Indicates that DTD validation should be used. DTD驗證模式*/public static final int VALIDATION_DTD = XmlValidationModeDetector.VALIDATION_DTD;/*** Indicates that XSD validation should be used. XSD驗證模式*/public static final int VALIDATION_XSD = XmlValidationModeDetector.VALIDATION_XSD;

XmlBeanDefinitionReader#detectValidationMode(Resource resource)函數是檢測資源文件的驗證模式的:

1 protected int detectValidationMode(Resource resource) { 2 // 如果資源已經被打開,則直接拋出異常 3 if (resource.isOpen()) { 4 throw new BeanDefinitionStoreException( 5 "Passed-in Resource [" + resource + "] contains an open stream: " + 6 "cannot determine validation mode automatically. Either pass in a Resource " + 7 "that is able to create fresh streams, or explicitly specify the validationMode " + 8 "on your XmlBeanDefinitionReader instance."); 9 } 10 11 // 打開InputStream流 12 InputStream inputStream; 13 try { 14 inputStream = resource.getInputStream(); 15 } catch (IOException ex) { 16 throw new BeanDefinitionStoreException( 17 "Unable to determine validation mode for [" + resource + "]: cannot open InputStream. " + 18 "Did you attempt to load directly from a SAX InputSource without specifying the " + 19 "validationMode on your XmlBeanDefinitionReader instance?", ex); 20 } 21 22 try { 23 // 檢測InputStream到底使用哪一種驗證模式 24 // 核心邏輯 25 return this.validationModeDetector.detectValidationMode(inputStream); 26 } catch (IOException ex) { 27 throw new BeanDefinitionStoreException("Unable to determine validation mode for [" + 28 resource + "]: an error occurred whilst reading from the InputStream.", ex); 29 } 30 }

其核心功能:檢測資源文件的驗證模式是委托給XmlValidationModeDetector#detectValidationMode(InputStream inputStream)

1 public int detectValidationMode(InputStream inputStream) throws IOException { 2 // 將InputStream進行包裝,便于讀取 3 // Peek into the file to look for DOCTYPE. 4 BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream)); 5 try { 6 // 是否為DTD驗證模式,默認為false,即不是DTD驗證模式,那就是XSD驗證模式 7 boolean isDtdValidated = false; 8 String content; 9 // 循環讀取xml資源的內容 10 while ((content = reader.readLine()) != null) { 11 // 消費注釋內容,返回有用信息 12 content = consumeCommentTokens(content); 13 // 如果為注釋,或者為空,則繼續循環 14 if (this.inComment || !StringUtils.hasText(content)) { 15 continue; 16 } 17 // #1.如果包含"DOCTYPE",則為DTD驗證模式 18 if (hasDoctype(content)) { 19 isDtdValidated = true; 20 break; 21 } 22 // #2.該方法會校驗,內容中是否有"<",并且"<"后面還跟著字母,如果是則返回true 23 // 如果為true,最終就是XSD模式 24 if (hasOpeningTag(content)) { 25 // End of meaningful data... 26 break; 27 } 28 } 29 // 返回DTD模式或XSD模式 30 return (isDtdValidated ? VALIDATION_DTD : VALIDATION_XSD); 31 } catch (CharConversionException ex) { 32 // Choked on some character encoding... 33 // Leave the decision up to the caller. 34 // 如果發生異常,則返回自動驗證模式 35 return VALIDATION_AUTO; 36 } finally { 37 reader.close(); 38 } 39 }

分析:

這里會遍歷資源的內容進行文件驗證模式的判斷

  • consumeCommentTokens(String line)
1 /** 2 * 注釋開始標志 <br/> 3 * The token that indicates the start of an XML comment. 4 */ 5 private static final String START_COMMENT = "<!--"; 6 7 /** 8 * 注釋結束標志"-->" <br/> 9 * The token that indicates the end of an XML comment. 10 */ 11 private static final String END_COMMENT = "-->"; 12 13 private String consumeCommentTokens(String line) { 14 // 非注釋,即為有用信息 15 if (!line.contains(START_COMMENT) && !line.contains(END_COMMENT)) { 16 return line; 17 } 18 String currLine = line; 19 // 消耗注釋內容,使循環跳向下一行 20 while ((currLine = consume(currLine)) != null) { 21 // 當inComment標志位更新,并且返回信息不是以注釋開始標志開始就返回currLine 22 if (!this.inComment && !currLine.trim().startsWith(START_COMMENT)) { 23 return currLine; 24 } 25 } 26 // 如果沒有有用信息,則返回null 27 return null; 28 }

分析:

  • 如果當前行不是注釋,則直接返回。
  • consume函數的主要作用是消耗注釋內容,繼續循環下一行的內容。
1 private String consume(String line) { 2 // 如果inComment:true,則走endComent函數;false,則走startComment函數,初始時為false 3 // 因此這里會走startComment,返回注釋位置的index[注釋位置+1的index] 4 int index = (this.inComment ? endComment(line) : startComment(line)); 5 // 如果index=-1,則表示沒有注釋信息,否則返回注釋信息 6 return (index == -1 ? null : line.substring(index)); 7 } 8 9 private int startComment(String line) { 10 // 返回注釋開始標志的位置信息 11 return commentToken(line, START_COMMENT, true); 12 } 13 14 private int endComment(String line) { 15 return commentToken(line, END_COMMENT, false); 16 } 17 18 private int commentToken(String line, String token, boolean inCommentIfPresent) { 19 // 查找注釋標志的開始位置[<!--或-->] 20 int index = line.indexOf(token); 21 // index>-1表示存在注釋開始標志,并將inComment更新為inCommentIfPresent 22 // [默認在startComment為true,endComment為false] 23 if (index > -1) { 24 this.inComment = inCommentIfPresent; 25 } 26 // 如果index=-1,則返回注釋標志的后一個位置信息index+token.length() 27 return (index == -1 ? index : index + token.length()); 28 }

分析:

  • consume函數意在消費注釋信息,繼續循環下一行的內容。
  • inComment用來標記當前內容是否為注釋,初始時為false,所以剛開始碰到一個注釋語句,會執行startComment(line),將inComment置為true,然后返回"<!--"后面的內容,此時inComment為true,則會繼續循環,此時會執行endComment(line),將inComment置為false,然后會返回"",在detectValidationMode函數中由于content="",此時會繼續循環,從而跳過注釋內容。

消費注釋信息這里稍微有點繞,通過下面流程圖可更好的理解:

文件驗證模式代碼分析完成,這里回到DefaultDocumentLoader#loadDocument:

1 public Document loadDocument(InputSource inputSource, 2 EntityResolver entityResolver, 3 ErrorHandler errorHandler, 4 int validationMode, 5 boolean namespaceAware) throws Exception { 6 // 創建DocumentBuilderFactory 7 DocumentBuilderFactory factory = createDocumentBuilderFactory(validationMode, namespaceAware); 8 if (logger.isTraceEnabled()) { 9 logger.trace("Using JAXP provider [" + factory.getClass().getName() + "]"); 10 } 11 // 創建DocumentBuilder對象 12 DocumentBuilder builder = createDocumentBuilder(factory, entityResolver, errorHandler); 13 // 通過DocumentBuilder解析InputSource,返回Document對象 14 // 解析xml文件的具體過程都是通過jdk內置的類進行解析的--DOMParser為其入口 15 return builder.parse(inputSource); 16 }

分析:

  • 首先根據驗證模式和是否支持命名空間創建DocumentBuilderFactory。
  • 然后創建DocumentBuilder對象。
  • 最后進行XML文件的解析,具體解析過程是利用jdk內置的DOMParser解析器進行解析。

DefaultDocumentLoader#createDocumentBuilderFactory:

1 protected DocumentBuilderFactory createDocumentBuilderFactory(int validationMode, boolean namespaceAware) 2 throws ParserConfigurationException { 3 // 創建DocumentBuilderFactory實例 4 DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); 5 // 設置是否支持命名空間 6 factory.setNamespaceAware(namespaceAware); 7 // 是否有校驗模式 8 if (validationMode != XmlValidationModeDetector.VALIDATION_NONE) { 9 // 開啟校驗模式 10 factory.setValidating(true); 11 // XSD模式下設置factory的屬性 12 if (validationMode == XmlValidationModeDetector.VALIDATION_XSD) { 13 // Enforce namespace aware for XSD... 14 // 如果為XSD模式,強制開啟命名空間支持 15 factory.setNamespaceAware(true); 16 try { 17 // 設置SCHEMA_LANGUAGE_ATTRIBUTE屬性為XSD 18 factory.setAttribute(SCHEMA_LANGUAGE_ATTRIBUTE, XSD_SCHEMA_LANGUAGE); 19 } catch (IllegalArgumentException ex) { 20 ParserConfigurationException pcex = new ParserConfigurationException( 21 "Unable to validate using XSD: Your JAXP provider [" + factory + 22 "] does not support XML Schema. Are you running on Java 1.4 with Apache Crimson? " + 23 "Upgrade to Apache Xerces (or Java 1.5) for full XSD support."); 24 pcex.initCause(ex); 25 throw pcex; 26 } 27 } 28 } 29 30 return factory; 31 }

分析:這里邏輯就非常簡單了,主要創建DocumentBuilderFactory對象,然后設置校驗模式等相關屬性。

DefaultDocumentLoader#createDocumentBuilder:

1 protected DocumentBuilder createDocumentBuilder(DocumentBuilderFactory factory, 2 @Nullable EntityResolver entityResolver, @Nullable ErrorHandler errorHandler) 3 throws ParserConfigurationException { 4 // 創建DocumentBuilder對象 5 DocumentBuilder docBuilder = factory.newDocumentBuilder(); 6 // 設置實體解析器 7 if (entityResolver != null) { 8 docBuilder.setEntityResolver(entityResolver); 9 } 10 // 設置錯誤處理器 11 if (errorHandler != null) { 12 docBuilder.setErrorHandler(errorHandler); 13 } 14 return docBuilder; 15 }

分析:根據DocumentBuilderFactory工廠創建DocumentBuilder對象,并設置實體解析器與錯誤處理器。

XML文件的具體解析利用了jdk內置的DOMParser類進行,這里就不在深入了。

到這里就得到了XML配置文件的Document實例,介于篇幅原因,注冊bean的過程將后面進行分析。

總結

這里總結下本文的重點:

  • Resource體系與ResourceLoader體系,加載資源這里比較重要,因為有了資源才能進行后面的BeanDefinition加載。
  • 檢測配置文件是如何確定文件的驗證模式,確定驗證模式這里做的比較巧妙,著重如何消費注釋信息繼續下一次循環。

by Shawn Chen,2018.12.5日,下午。

轉載于:https://www.cnblogs.com/developer_chan/p/10013846.html

總結

以上是生活随笔為你收集整理的【spring源码分析】IOC容器初始化(二)的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。