Spring 管理连接池

要想管理连接池,首先得导入数据库相关包,这里就不多说了。

我们这里采取配置文件的方式写入配置

user=root
password=123
jdbcUrl=jdbc:mysql://localhost:3306/bjpowernode
driverClass=com.mysql.jdbc.Driver

这里有一个坑,那就是注意不要写username,因为 username代表的是当前用户的名称,而不是你数据库连接的用户名

下面是配置文件

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context
              http://www.springframework.org/schema/context/spring-context-4.2.xsd">

    <context:property-placeholder location="classpath:db.properties"/>

    <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
        <property name="user" value="${user}"></property>
        <property name="password" value="${password}"></property>
        <property name="jdbcUrl" value="${jdbcUrl}"></property>
        <property name="driverClass" value="${dirverClass}"></property>
    </bean>

</beans>

需要注意的是,要想用配置文件的方式进行配置的话,得引用外部配置文件,依赖context名称空间:

       xmlns:context="http://www.springframework.org/schema/context"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context
              http://www.springframework.org/schema/context/spring-context-4.2.xsd"

然后就可以进行测试了

    @Test
    public void connectionTest() throws SQLException {
        ApplicationContext context = new ClassPathXmlApplicationContext("bean.xml");
        DataSource dataSource = (DataSource) context.getBean("dataSource");
        System.out.println(dataSource.getConnection());
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值