首页 > 代码库 > MyBatis源码学习--配置文件的加载
MyBatis源码学习--配置文件的加载
先从XmlConfigBuilder开始
private void parseConfiguration(XNode root) {
try {
this.propertiesElement(root.evalNode("properties"));
this.typeAliasesElement(root.evalNode("typeAliases"));
this.pluginElement(root.evalNode("plugins"));
this.objectFactoryElement(root.evalNode("objectFactory"));
this.objectWrapperFactoryElement(root.evalNode("objectWrapperFactory"));
this.reflectionFactoryElement(root.evalNode("reflectionFactory"));
this.settingsElement(root.evalNode("settings"));
this.environmentsElement(root.evalNode("environments"));
this.databaseIdProviderElement(root.evalNode("databaseIdProvider"));
this.typeHandlerElement(root.evalNode("typeHandlers"));
this.mapperElement(root.evalNode("mappers"));
} catch (Exception var3) {
throw new BuilderException("Error parsing SQL Mapper Configuration. Cause: " + var3, var3);
}
}
上面的代码加载mybatis-config.xml中的各个字节点的内容,以this.propertiesElement(root.evalNode("properties")), 其中具体的内容是
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 = this.configuration.getVariables();
if(vars != null) {
defaults.putAll(vars);
}
this.parser.setVariables(defaults);
this.configuration.setVariables(defaults);
}
}
其功能是获取<properties resource="mysql-config.properties" />的内容, 其中resource和URL不能并存,否则就会抛出异常,
因为加载数据库相关信息有两种方式,所以根据if判断进入不同的信息,其他的标签也类似。接下来跟踪defaults.putAll(Resources.getResourceAsProperties(resource));
具体的内容是
public static Properties getResourceAsProperties(String resource) throws IOException {
Properties props = new Properties();
InputStream in = getResourceAsStream(resource);
props.load(in);
in.close();
return props;
}
结果是返回引入的properties文件的内容,然后保存可用的信息。
MyBatis源码学习--配置文件的加载