mybatis 啟動流程原始碼分析(二)之 Configuration-Properties解析
阿新 • • 發佈:2020-09-15
一. 配置檔案
參考: https://www.cnblogs.com/wanthune/p/13674243.html
二. 原始碼解析
- XMLConfigBuilder 就是解析Xml的主類。
public Configuration parse() { if (parsed) { throw new BuilderException("Each XMLConfigBuilder can only be used once."); } parsed = true; parseConfiguration(parser.evalNode("/configuration")); return configuration; } // 第一步,解析properites節點 private void parseConfiguration(XNode root) { try { //issue #117 read properties first propertiesElement(root.evalNode("properties")); Properties settings = settingsAsProperties(root.evalNode("settings")); loadCustomVfs(settings); typeAliasesElement(root.evalNode("typeAliases")); pluginElement(root.evalNode("plugins")); objectFactoryElement(root.evalNode("objectFactory")); objectWrapperFactoryElement(root.evalNode("objectWrapperFactory")); reflectorFactoryElement(root.evalNode("reflectorFactory")); settingsElement(settings); // read it after objectFactory and objectWrapperFactory issue #631 environmentsElement(root.evalNode("environments")); databaseIdProviderElement(root.evalNode("databaseIdProvider")); typeHandlerElement(root.evalNode("typeHandlers")); mapperElement(root.evalNode("mappers")); } catch (Exception e) { throw new BuilderException("Error parsing SQL Mapper Configuration. Cause: " + e, e); } } // 解析properties節點 private void propertiesElement(XNode context) throws Exception { if (context != null) { // 讀取properties節點,返回一個Properties物件 Properties defaults = context.getChildrenAsProperties(); // 讀取resource屬性值 String resource = context.getStringAttribute("resource"); // 讀取url屬性值 String url = context.getStringAttribute("url"); // 這兒就是為什麼不能在檔案中同時配置resource和url,同時配置時拋異常 if (resource != null && url != null) { throw new BuilderException("The properties element cannot specify both a URL and a resource based property file reference. Please specify one or the other."); } // 優先獲取resource,之所以先判斷Resource,我覺得是因為本地檔案讀取的更快。 if (resource != null) { defaults.putAll(Resources.getResourceAsProperties(resource)); } else if (url != null) { // 從遠端url中讀取檔案流 defaults.putAll(Resources.getUrlAsProperties(url)); } Properties vars = configuration.getVariables(); if (vars != null) { defaults.putAll(vars); } // 將讀取到的屬性值放到parser(XPathParser)中 parser.setVariables(defaults); // 同時也放入configuration中。 configuration.setVariables(defaults); } }