错误背景:测试SpringJDBC时创建了一个bean叫做Person,通过PersonService和PersonDao的操作将一个Person对象保存进入数据库。
具体代码:
//PersonDao类
package com.tt.springjdbc;
import org.springframework.jdbc.core.support.JdbcDaoSupport;
public class PersonDao extends JdbcDaoSupport implements PersonInter{
public void savePerson(){
this.getJdbcTemplate().execute("update person set pname='shuai ge' where pid=3");
}
}
//PersonService接口:
package com.tt.springjdbc;
public interface PersonService {
public void savePerson();
}
//PersonService接口的实现类:
package com.tt.springjdbc;
public class PersonServiceImpl implements PersonService{
private PersonDao personDao;
public PersonDao getPersonDao() {
return personDao;
}
public void setPersonDao(PersonDao personDao) {
this.personDao = personDao;
}
public void savePerson() {
// TODO Auto-generated method stub
this.personDao.savePerson();
}
}
//导致错误的关键配置文件信息:
<bean id="personDao" class="com.tt.springjdbc.PersonDao">
<property name="dataSource">
<ref bean="dataSource"/>
</property>
</bean>
<bean id="personService" class="com.tt.springjdbc.PersonServiceImpl">
<property name="personDao">
<ref bean="personDao"/>
</property>
</bean>
报错信息:
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'personService' defined in class path resource [applicationContext.xml]:
Initialization of bean failed; nested exception is org.springframework.beans.TypeMismatchException: Failed to convert property value of type [$Proxy4 implementing com.tt.springjdbc.PersonInter,org.springframework.beans.factory.InitializingBean,org.springframework.aop.SpringProxy,
org.springframework.aop.framework.Advised] to required type [com.tt.springjdbc.PersonDao] for property 'personDao'; nested exception is java.lang.IllegalArgumentException: Cannot convert value of type [$Proxy4 implementing
com.tt.springjdbc.PersonInter,org.springframework.beans.factory.InitializingBean,org.springframework.aop.SpringProxy,
org.springframework.aop.framework.Advised] to required type [com.tt.springjdbc.PersonDao] for property 'personDao':
no matching editors or conversion strategy found
错误原因:出错后百度这个错误信息,在一位大神的博客里找到了答案。原因在于PersonService中保存的应该是一个接口,而我当时为了省事就直接把PersonDao写成了一个类,没有定义接口。
错误改正:得知了错误原因之后,我写了一个接口叫做PersonInter,用PersonDao当做它的实现类,并且在PersonServiceImpl中保存PersonInter,并且相应地在配置文件中进行了修改,于是错误被解决。
排错感悟:排除了这个错误之后真真切切地体会到了Spring是一个完全的面向接口编程的框架,这样实现了解耦,带来了极大的灵活性,真的佩服框架的设计师,牛。