上一篇介绍了Spring的JdbcTemplate在Java或者JavaWeb项目中的使用,没有使用配置文件,本文介绍如何在spring的配置文件中配置数据源和JdbcTemplate,以及如何使用JdbcTemplate
数据库还是上篇博客的数据库,项目也是上篇项目名。请参考:Spring的数据库开发之一--JDBC模板的使用
1.引入spring的配置文件,在这里将配置文件放在包里,名字叫bean1.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"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-2.0.xsd">
<!-- 配置数据源 -->
<bean id="dataSource"
class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver"/>
<property name="url" value="jdbc:mysql:///spring?useUnicode=true&characterEncoding=UTF-8"/>
<property name="username" value="root"/>
<property name="password" value="root"/>
</bean>
<bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
<property name="dataSource" ref="dataSource"/>
</bean>
</beans>
在上篇博文中的测试代码,同本篇的配置文件的关系,如下图所示。
2. 测试代码
@Test
public void demo2() {
//1.获得spring工厂
String configLocation = "cn/zdxh/jdbc/demo1/bean1.xml";
ApplicationContext ac = new ClassPathXmlApplicationContext(configLocation);
//2.得到jdbcTemplate实例
JdbcTemplate jdbcTemplate = ac.getBean(JdbcTemplate.class);
String sql="insert into account values(null,?,?)";
int update = jdbcTemplate.update("insert into account values(null,?,?)", "张三",10000d);
}
3.测试结果
总结:本文使用spring的配置文件使用JdbcTemplate,并且将配置文件的属性同上篇的测试代码进行了对比说明,以便大家对配置的属性来源有个了解。
下一篇将要在此基础上对JdbcTemplate的常用方法进行介绍。