接着上一篇mybatis 3.5.x源码系列(1) 我们继续研究一下mybatis的配置读取
properties
上一篇我们讲到了xml解析1
org.apache.ibatis.builder.xml.XMLConfigBuilder#parseConfiguration(org.apache.ibatis.parsing.XNode root)
这里我们来看看这个方法中的第一步1
org.apache.ibatis.builder.xml.XMLConfigBuilder#propertiesElement(org.apache.ibatis.parsing.XNode context)
可以看到propertiesElement接收的参数是root.evalNode(“properties”)
那么我们看看properties是如何编写?1
2
3
4<properties resource="org/mybatis/example/config.properties">
<property name="username" value="dev_user"/>
<property name="password" value="F2Fa3!33TYyg"/>
</properties>
实际上在properties上有两个属性 resource和url,但是这两个属性不能同时使用1
2
3
4
5String 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.");
}
resource
1 | org.apache.ibatis.io.Resources#getResourceAsProperties(java.lang.String) |
这里会分别从classLoader
, defaultClassLoader
, Thread.currentThread().getContextClassLoader()
, getClass().getClassLoader()
, ClassLoader.getSystemClassLoader()
加载resource指定的properties文件
一般情况下:Thread.currentThread().getContextClassLoader()
,getClass().getClassLoader()
,ClassLoader.getSystemClassLoader()
都是Launcher$AppClassLoader
url
1 | org.apache.ibatis.io.Resources#getUrlAsProperties(java.lang.String) |
url的加载就比较简单了,采用的java.net.URL#openConnection()的方式加载配置文件
jdk的URL有这些:http(s), jar, file, ftp等等,具体的就是java.net.URLConnection的实现类
无论是resource加载还是url加载,最终加载到配置文件后,把所有解析到的值存放到mybatis默认的defaults properties中
settings, typeAliases, typeHandlers, objectFactory
如何使用,大家可以看看settings
typeAliases
typeHandlers
objectFactory
好了,下次见。
本文标题:mybatis 3.5.x源码系列(2)
本文链接:https://xxzkid.github.io/2020/mybatis-source-02/