Java jdbctemplate赋值_给dao层注入jdbcTemplate时的一个强行bug(jdbcDaoSupport不要随便用!用了要记得!)...
记录Dao层一个鱼唇至极的错误
这一天我在使用Spring的进行注解配置项目时,
我的Idea给我抛了一个如下的错误:
Exception in thread "main" org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'accountDaoImpl' defined in file [D:ideaworksday53_spring4demo03targetclassescomjxkdaoimplAccountDaoImpl.class]: Invocation of init method failed;
nested exception is java.lang.IllegalArgumentException:
'dataSource' or 'jdbcTemplate' is required
一开始看到这个错误,我赶紧又看了一下我的配置文件:
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:context="http://www.springframework.org/schema/context"
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.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd">
感觉没啥毛病啊,难道是spring提供的内置数据源有问题?
于是我就把上边的数据源替换成c3p0的…...
一运行––-—--
'dataSource' or 'jdbcTemplate' is required
难道是注解有干扰?于是在@Autowired下边添加了一个@Qualifier
@Repository
public class AccountDaoImpl extends JdbcDaoSupport implements AccountDao {
@Autowired
@Qualifier(value = "jdbcTemplate")
private JdbcTemplate jdbcTemplate;
但还是没有效果..….
但其实,bug就在上边的几行代码里…....
因为copy-paste的原因...我的Dao层实例竟然继承了一个JdbcDaoSupport类!!!
继承这个类的话就可以使用它内置的一个getJdbcTemplate方法,而不用再自己创建一个jdbcTemplate属性.….但是这个继承这个类以后,再去创建自己的jdbcTemplate会怎么样呢?恭喜我,成功为自己制造了一个bug..….
如果要使用注释注入,就不要在继承这个类了呀!!!,
报错的原因正是
我给AccountDaoImpl注入了jdbcTemplate,但它继承的父类JdbcDaoSupport里边的jdbcTemplate却还是空的!!!!
如果非要作,还是要继承这个类的话,可以这样!!!:
@Repository
public class AccountDaoImpl extends JdbcDaoSupport implements AccountDao {
@Autowired
private JdbcTemplate jdbcTemplate;
//在这里,给dao层实例的父类的jdbcTemplate也赋值!!!
@Autowired
private void setSuperDataSources(ComboPooledDataSource dataSources){
super.setDataSource(dataSources);
}
copy一时爽!!!!!一直copy一直爽!!!
啊!我的时间!我的头发!