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>