mybatis中提供了3中配置方式
- property 子元素
- properties配置文件
- 程序参数传递
property子元素的配置方式
<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="learn"/>
</properties>
这样我们就可以在配置文件中直接使用已经配置好的属性值了
<dataSource type="POOLED">
<property name="driver" value="${driver}"/>
<property name="url" value="${url}"/>
<property name="username" value="${username}"/>
<property name="password" value="${password}"/>
properties 配置文件
driver=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/mybatis
username=root
password=learn
使用时,我们把properties文件放在源包下,
引入mybatis的配置文件sqlMapConfig.xml中即可
<properties resource="jdbc.properties"/>
程序参数传递
在实际情况中,系统由运维人员去配置,生产数据库的密码对生产者是保密的,为了安全,运维人员会要求对配置文件中的用户名及密码加密,这样我们配置文件中往往配置的是加密过后的数据库信息,而无法通过加密的字符串去连接数据库,这个时候可以通过编码的形式来满足我们遇到的场景.
假设解密的方法decode(str)
InputStream inputStream=null;
Reader cfgReader=null;
InputStream proStream=null;
Reader proReader=null;
Properties properties=null;
try{
//读入配置的文件流
cfgStream=Resources.getResourceAsStream("mybatis-config.xml");
cfgReader=new InputStreamReader(cfgStream);
//读入属性文件
proStream=Resoources.getResourceAsStream("jdbc.properties");
proReader=neew InputStreamReader(proStream);
properties=new Properties();
properties.load(proReader);
//解密为明文
properties.setProperty("username",decode(properties.getProperty("username")));
properties.setProperty("password",properties.getProperty("password"));
}catch(IOException ex){
Logger.getLogger(sqlSessionFactoryUtils.class.getName().log(level.SEVERE,NULL,ex));
}
synchronized(CLASS_LOCK){
if(sqlSessionFactory==null){
//使用属性来创建
sqlSessionFactory=new SqlSessionFactoryBuilder().build(cfgReader,properties);
}
}
3种配置方式同时出现时,优先级
mybatis按照以下顺序加载
1. 在properties元素体内指定的属性优先被读取
2. 根据properties元素中的resource属性读取类路径下属性文件.或者根据url属性指定的路径读取属相文件,并覆盖已读取的同名属性.
3. 读取作为方法参数传递的属性,并覆盖已读取的同名属性
因此,通过方法参数传递的属性具有最高优先级,resource/url属性中指定的配置文件次之,最低优先级是properties属性中指定的属性.
注意事项:
1. 不要使用混合方式,这样会使管理混乱
2. 首选方式是使用properties文件
3. 如果我们需要对其进行加密或者其他加工满足特殊的要求,不妨按照市里的方法进行处理,这样做的好处是是的配置都来自同