分析java
MyBatis整合Spring的实现(3)中能够知道,XMLConfigBuilder类读取MyBatis的全局配置文件信息转成Document,具体的把Document转成JAVA类,作了哪些操做呢?下面就来分析XMLConfigBuilder的解析。app
MyBatis整合Spring的实现(1)中代码实现的4.7,建立事务在后面文章会介绍。ide
1 入口
ui
public Configuration parse() { if (parsed) { throw new BuilderException("Each XMLConfigBuilder can only be used once."); } parsed = true; parseConfiguration(parser.evalNode("/configuration")); return configuration; }
上述代码,若是文件已经被解析,也就是会抛出异常。这里解析直接返回Configuration(全局配置类),由于Configuration(全局配置类)是成员变量,因此在方法parseConfiguration中进行设置值也是没有问题的。下面就分析一下具体解析代码。
url
2 方法parseConfigurationspa
private void parseConfiguration(XNode root) { try { propertiesElement(root.evalNode("properties")); //issue #117 read properties first typeAliasesElement(root.evalNode("typeAliases")); pluginElement(root.evalNode("plugins")); objectFactoryElement(root.evalNode("objectFactory")); objectWrapperFactoryElement(root.evalNode("objectWrapperFactory")); settingsElement(root.evalNode("settings")); environmentsElement(root.evalNode("environments")); // read it after objectFactory and objectWrapperFactory issue #631 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); } }
上述代码太多了,看着头晕,因此来进行分解,对propertiesElement(root.evalNode("properties"));进行分析(这里的解析是对MyBatis的全局配置文件而不是Spring的配置文件)。上面的方法都是XMLConfigBuilder类的内部方法。.net
3 方法propertiesElementcode
private void propertiesElement(XNode context) throws Exception { if (context != null) { Properties defaults = context.getChildrenAsProperties(); String resource = context.getStringAttribute("resource"); String url = context.getStringAttribute("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."); } if (resource != null) { defaults.putAll(Resources.getResourceAsProperties(resource)); } else if (url != null) { defaults.putAll(Resources.getUrlAsProperties(url)); } Properties vars = configuration.getVariables(); if (vars != null) { defaults.putAll(vars); } parser.setVariables(defaults); configuration.setVariables(defaults); } }
做者没有使用过properties,根据上面代码,反推出下面配置信息。从全局配置文件中获取有哪些配置信息,在读取properties文件,resource与url只能设置一个,不然抛异常。最后把"全局配置类"原有的属性和获取的属性合并。orm
4 MyBatis全局配置XML文件xml
<configuration> <properties resource="dbc.properties"> <property name="test" value="test"/> </properties> </configuration>
总结:
MyBatis的解析是最重要的一部分,目前只是对全局配置文件进行解析,后面还有对SQL进行解析,解析的步骤也很是的多,类的嵌套也很是多,可是思路必定要清晰。
Configuration(全局配置类)是最后解析全部配置所存在的最终信息。里面的不一样属性,在MyBatis内部有不一样的功能,这里的parseConfiguration方法内部的方法,分解成每一个小方法去分析,这样就不会看了后面而不知道,当前变量究竟是哪里来的,变量是要作什么的。