properties的使用方法。
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
<!-- 方法一: 从外部指定properties配置文件, 除了使用resource属性指定外,还可通过url属性指定url-->
<properties resource="dbConfig.properties"></properties>-
<!-- 方法二: 直接配置为xml -->
<properties>
<property name="driver" value="com.mysql.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://localhost:3306/mybatis"/>
<property name="username" value="root"/>
<property name="password" value="adminter"/>
</properties>
</configuration>
dbConfig.properties的内容
driver=com.mysql.jdbc.Driver
urlvalue=jdbc:mysql://localhost:3306/mybatis
username=root
passwordv=adminter
我要是 两种方法都同时用了,那么哪种方法优先?
当以上两种方法都xml配置优先, 外部指定properties配置其次。
properties的解析过程
private void propertiesElement(XNode context) throws Exception {
if (context != null) {
//先解析xml配置文件中的Properties元素
Properties defaults = context.getChildrenAsProperties();
// 解析外部的properties文件
String resource = context.getStringAttribute("resource");
String url = context.getStringAttribute("url");
// 如果引入外部properties的标签的URL属性和resource属性都存在则报错
// 因为,这样会影响判断外部文件的位置
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.");
}
//将configuration对象中已配置的Properties属性与刚刚解析的融合
if (resource != null) {
defaults.putAll(Resources.getResourceAsProperties(resource));
} else if (url != null) {
defaults.putAll(Resources.getUrlAsProperties(url));
}
//此处的向后顺序决定了xml中的优先级高于外部的propertise文件
Properties vars = configuration.getVariables();
if (vars != null) {
defaults.putAll(vars);
}
//把装有解析配置propertis对象set进解析器, 因为后面可能会用到
parser.setVariables(defaults);
//设置configuration属性
configuration.setVariables(defaults);
}
}
Properties是由hashTable实现的,hashTable的putAll()方法是循环调用put()方法,
put方法的在放的时候,会检查key是否存在,如果存在的话,就不添加新值
public synchronized V put(K key, V value) {
// Make sure the value is not null
if (value == null) {
throw new NullPointerException();
}
// Makes sure the key is not already in the hashtable.
Entry<?,?> tab[] = table;
int hash = key.hashCode();
int index = (hash & 0x7FFFFFFF) % tab.length;
@SuppressWarnings("unchecked")
Entry<K,V> entry = (Entry<K,V>)tab[index];
for(; entry != null ; entry = entry.next) {
if ((entry.hash == hash) && entry.key.equals(key)) {
V old = entry.value;
entry.value = value;
return old;
}
}
addEntry(hash, key, value, index);
return null;
}