spring jdbc模板的配置小差异

1.当我们使用jdbcTemplate配置spring时,会有一些微小的差异,自己在这个问题上纠结了一会,希望大家遇到之后可以避免

①jdbcTemplate模板配置

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

<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
	<property name="driverClassName" value="com.mysql.jdbc.Driver"></property>
	<property name="url" value="jdbc:mysql://localhost:3306/test"></property>
	<property name="username" value="root"></property>
	<property name="password" value="tokuzozo"></property>
</bean>

<bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
	<span style="color:#FF0000;"><property name="dataSource" ref="dataSource"></property></span>
</bean>

<bean id="rantDao" class="com.sh.datasource.JdbcRantDao">
	<property name="jdbcTemplate" ref="jdbcTemplate"></property>
</bean>

</beans>	
注意红色字体的配置可以是因为JdbcTemplate类

JdbcTemplate extends JdbcAccessor implements JdbcOperations

在JdbcAccessor类中有dataSource属性,所以property注入没有问题

private DataSource dataSource;
public void setDataSource(DataSource dataSource) {
        this.dataSource = dataSource;
    }

②然而,当使用SimpleJdbcTemplate和NameParameterJdbcTemplate类时候,由于没有dataSource属性所以只能在构造方法中注入

最初和上面一样配置时候出现

Could not instantiate bean class

[org.springframework.jdbc.core.simple.SimpleJdbcTemplate]:

No default constructor found; nested exception is java.lang.

NoSuchMethodException: org.springframework.jdbc.core.simple.SimpleJdbcTemplate.<init>()

解决问题修改如下

<bean id="jdbcTemplate" class="org.springframework.jdbc.core.simple.SimpleJdbcTemplate">
	<span style="color:#FF0000;"><del><property name="dataSource" ref="dataSource"></property></del>
	<constructor-arg ref="dataSource"></constructor-arg></span>
</bean>
因为在SimpleJdbcTemplate中没有setDataSource 而存在构造方法

public class SimpleJdbcTemplate implements SimpleJdbcOperations {
public SimpleJdbcTemplate(DataSource dataSource) {
		this.namedParameterJdbcOperations = new NamedParameterJdbcTemplate(dataSource);
	}
}







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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值