十六、Spring通过IOC管理JDBC模板

直接上操作步骤

在上一篇文章十五、Spring的JDBC模板类入门的基础上继续添加2个jar包便于测试
spring-aop-4.2.4.RELEASE.jar
spring-test-4.2.4.RELEASE.jar

完整的jar包如下
在这里插入图片描述

接着,在src下添加applicationContext.xml和log4j.properties配置文件
在上一篇文章中,我们使用的是直接在代码中通过手动new的方式创建连接池和模板类,这次我将通过配置文件的方式交给Spring框架来管理。

完整的applicationContext.xml配置如下:

<?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:aop="http://www.springframework.org/schema/aop"
	xsi:schemaLocation="
        http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd"> 

	<!-- 注册Spring管理内置的连接池 -->
	<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
		<!-- 注入属性值,具体的name就是对应setXxx中的xxx -->
		<property name="driverClassName" value="com.mysql.jdbc.Driver" />
		<property name="url" value="jdbc:mysql:///spring_jdbc" />
		<property name="username" value="root" />
		<property name="password" value="1234" />

	</bean>
	
	<!-- 注册Spring管理模板类 -->
	<bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
		<!-- 注入属性值,引用类型属性用ref -->
		<property name="dataSource" ref="dataSource"/>
	</bean>
</beans>

测试

package blog.csdn.net.mchenys.test;

import javax.annotation.Resource;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:applicationContext.xml")
public class Demo1 {

	//通过java注解注入模板
	@Resource(name="jdbcTemplate")
	private JdbcTemplate JdbcTemplate;
	
	@Test
	public void test1() {
		JdbcTemplate.update("update t_account set money=? where name=?",99,"胜哥");
	}
}

运行测试类的测试方法后,查看数据库,如果值发生 改变,这说明配置成功
在这里插入图片描述

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值