MyBatis 使用阿里的Druid连接池

MyBatis默认提供了一个数据库连接池PooledDataSource,一般我们只需要在配置文件中配置,然后就可以使用

 <dataSource type="POOLED" >
        <property name="driver" value="${driver}"/>
        <property name="url" value="${url}"/>
        <property name="username" value="${username}"/>
        <property name="password" value="${password}"/>
</dataSource>

如果想更换其他的数据库连接池,比如Druid,这里介绍一种方法。

只需要两步:

1、创建连接池工厂-----继承PooledDataSourceFactory

public class DruidDataSourceFactory extends PooledDataSourceFactory {
    public DruidDataSourceFactory() {
        this.dataSource = new DruidDataSource();
    }
}

虽然Druid提供了一个同名的DruidDataSourceFactory类,但是不能在MyBatis中直接使用。

 

2、修改配置文件

<dataSource type="com.gyb.mybatis.common.DruidDataSourceFactory" >
        <property name="driverClass" value="${driver}"/>
        <property name="jdbcUrl" value="${url}"/>
        <property name="username" value="${username}"/>
        <property name="password" value="${password}"/>
</dataSource>

注意:这里的 property配置需要根据你选择的数据库连接池的具体实现做调整, Druid需要改成上面的配置。因为MyBatis时通过调用数据源的具体实现类的属性的setter方法进行值注入的。查看DruidAbstractDataSource源码,你会发现有以下属性

protected volatile String username;
protected volatile String password;
protected volatile String jdbcUrl;
protected volatile String driverClass;

并提供了setter方法。

  • 6
    点赞
  • 34
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值