mybatis 启动流程源码分析(二)之 Configuration-Properties解析
一. 配置文件
参考: 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);
}
}