分析
MyBatis整合Spring的实现(3)中可以知道,XMLConfigBuilder类读取MyBatis的全局配置文件信息转成Document,具体的把Document转成JAVA类,做了哪些操作呢?下面就来分析XMLConfigBuilder的解析。
MyBatis整合Spring的实现(1)中代码实现的4.7,创建事务在后面文章会介绍。
1 入口
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中进行设置值也是没有问题的。下面就分析一下具体解析代码。
2 方法parseConfiguration
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类的内部方法。
3 方法propertiesElement
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只能设置一个,否则抛异常。最后把"全局配置类"原有的属性和获取的属性合并。
4 MyBatis全局配置XML文件
<configuration> <properties resource="dbc.properties"> <property name="test" value="test"/> </properties> </configuration>
总结:
MyBatis的解析是最重要的一部分,目前只是对全局配置文件进行解析,后面还有对SQL进行解析,解析的步骤也非常的多,类的嵌套也非常多,但是思路一定要清晰。
Configuration(全局配置类)是最后解析所有配置所存在的最终信息。里面的不同属性,在MyBatis内部有不同的功能,这里的parseConfiguration方法内部的方法,分解成每个小方法去分析,这样就不会看了后面而不知道,当前变量到底是哪里来的,变量是要做什么的。
原文:http://my.oschina.net/u/1269959/blog/521815