Spring 通过注解的方式配置C3P0数据源

第一步:修改applicationContext.xml文件的配置

<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.xsd "> </beans>

作用:引入context命名空间和约束路径

第二步:在applicationContext.xml中加载properties配置文件

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

property-placeholder的意思大概就是引入位置

作用:将配置文件中的值存到Spring容器中

第三步:在applicationContext.xml中配置c3p0连接池bean对象

<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">

<!-- 通过set方式在连接池对象中注入值 其中的${}为Spring表达式,用法和EL表达式相同作用是取出Spring容器中的值-->

<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>

第四步:开始测试

@Test

public void test() throws PropertyVetoException, SQLException, IOException {

// c创建ApplicationContext对象 然后由Spring帮我们创建ComboPooledDataSource对象 ApplicationContextapplicationContext=newClassPathXmlApplicationContext("applicationContext.xml");

ComboPooledDataSource ds =(ComboPooledDataSource)applicationContext.getBean("dataSource");

connection = ds.getConnection(); queryRunner = new QueryRunner(ds); System.out.println(connection);

}

获取结果:成功!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值