fast config for ComboPooledDataSource

spring环境下,c3p0数据库连接池简易工厂类

import com.mchange.v2.c3p0.ComboPooledDataSource;
import org.springframework.beans.factory.FactoryBean;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.core.io.UrlResource;
import org.springframework.core.io.support.PropertiesLoaderUtils;
import org.springframework.util.Assert;
import org.springframework.util.ResourceUtils;

import java.beans.PropertyVetoException;
import java.util.Properties;

/**
 * Created by guor on 2015/3/19.
 */
public class C3P0DataSourceFactoryBean implements FactoryBean<ComboPooledDataSource>, InitializingBean {
    private String resourceLocation;
    private ComboPooledDataSource dataSource;

    @Override
    public ComboPooledDataSource getObject() throws Exception {
        return this.dataSource;
    }

    @Override
    public Class<?> getObjectType() {
        return ComboPooledDataSource.class;
    }

    @Override
    public boolean isSingleton() {
        return false;
    }

    @Override
    public void afterPropertiesSet() throws Exception {
        Assert.notNull(this.getResourceLocation(), "resourceLocation cannot be null.");
        Properties p = PropertiesLoaderUtils.loadProperties(new UrlResource(ResourceUtils.getURL(getResourceLocation())));
        try {
            this.dataSource = initC3p0Properties(p);
        } catch (PropertyVetoException e) {
            throw new Exception("初始化数据库连接池失败.", e);
        }
    }

    private ComboPooledDataSource initC3p0Properties(Properties prop) throws PropertyVetoException {
        ComboPooledDataSource ds = new ComboPooledDataSource(false);
        ds.setJdbcUrl(prop.getProperty("jdbcUrl"));
        ds.setUser(prop.getProperty("user"));
        ds.setPassword(prop.getProperty("password"));
        ds.setDriverClass(prop.getProperty("driverClass"));
        ds.setMaxIdleTime(Integer.parseInt(prop.getProperty("maxIdleTime")));
        ds.setMaxPoolSize(Integer.parseInt(prop.getProperty("maxPoolSize")));
        ds.setMinPoolSize(Integer.parseInt(prop.getProperty("minPoolSize")));
        ds.setInitialPoolSize(Integer.parseInt(prop.getProperty("initialPoolSize")));
        ds.setAcquireIncrement(Integer.parseInt(prop.getProperty("acquireIncrement")));
        return ds;
    }

    public String getResourceLocation() {
        return resourceLocation;
    }

    public void setResourceLocation(String resourceLocation) {
        this.resourceLocation = resourceLocation;
    }
}

使用范例:

<bean id="dataSource" class="com.peony.C3P0DataSourceFactoryBean">
    <property name="resourceLocation" value="classpath:jdbc.properties"/>
</bean>
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值