目录
数据连接池的作用
数据源的配置步骤
使用spring配置数据源
/**
* 测试手动创建c3po数据连接
*
*/
@Test
public void test() throws PropertyVetoException, SQLException {
ComboPooledDataSource dataSource = new ComboPooledDataSource();
dataSource.setDriverClass("com.mysql.jdbc.Driver");
dataSource.setJdbcUrl("jdbc:mysql://localhost:3306/test");
dataSource.setUser("root");
dataSource.setPassword("123");
Connection connection = dataSource.getConnection();
System.out.println(connection);
connection.close();
}
<bean name="rb" class="com.mchange.v2.c3p0.ComboPooledDataSource">
<property name="driverClass" value="com.mysql.jdbc.Driver"></property>
<property name="jdbcUrl" value="jdbc:mysql://localhost:3306/test"></property>
<property name="user" value="root"></property>
<property name="password" value="123"></property>
</bean>
主要是通过spring-bean方法中的通过set发法注入属性来进行
/**
* 测试spring创建数据连接
*/
@Test
public void test4() throws SQLException {
ApplicationContext app=new ClassPathXmlApplicationContext("applicationContext.xml");
DataSource rb = (DataSource) app.getBean("rb");
Connection connection = rb.getConnection();
System.out.println(connection);
connection.close();
}
抽取配置文件
在使用spring进行数据源配置的时候就已经进行了解耦了,但是为了更加方便所以对jdbc的配置进行了抽取
定义命名空间
xmlns:contest="http://www.springframework.org/schema/context"
http://www.springframework.org/schema/context http://www.springframework.org/schema/contest/spring-contest.xsd
<contest:property-placeholder location="classpath:jdbc.properties"/>
使用
<bean name="rb" class="com.mchange.v2.c3p0.ComboPooledDataSource">
<property name="driverClass" value="${jdbc.driver}"></property>
<property name="jdbcUrl" value="${jdbc.url}"></property>
<property name="user" value="${jdbc.username}"></property>
<property name="password" value="${jdbc.password}"></property>
</bean>