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);
}
}