直接上操作步骤
在上一篇文章十五、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,"胜哥");
}
}
运行测试类的测试方法后,查看数据库,如果值发生 改变,这说明配置成功