现在的位置: 首页 > 综合 > 正文

spring 继承的baseDao无法注入导致异常的问题

2018年02月01日 ⁄ 综合 ⁄ 共 1333字 ⁄ 字号 评论关闭

今天在baseService<T> 中注入了baseDao<T>  

public abstract class BaseService { @Resource private BaseDao baseDao ; .................................. }

然后一运行出错 

Error creating bean with name 'userService':

                  Injection of resource dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException:

 Error creating bean with name 'baseDao': FactoryBean threw exception on object creation; nested exception is java.lang.IllegalArgumentException: Not an managed type: class java.lang.Object

记得前几天在spring中配置 domainClassConveter的时候也是这个错误 ,当时弄了半天没弄出来 ,直接注掉了...羞愧

这次又查了下资料 ,发现是泛型的问题,

在baseDao用Resource注入后,在具体实现时(比如用ioc得到userService时),没提供具体的T类型 ,而spring注入baseDao<T> - 即baseDao<Object>会发生错误(具体原因不甚明确)

解决方案是  :

    public abstract class BaseService <T> {

private BaseDao<T> baseDao ;   //在这里不进行注入,而实现set方法

public void setBaseDao(BaseDao<T> baseDao) {
this.baseDao = baseDao;
}
public void saveOrUpdate  (T entity) {
baseDao.save(entity) ; 
}
public void delete (T entity) {
baseDao.delete(entity) ;
}
public void delete(Long id){
baseDao.delete(id) ;
}

public T findOne (Long id ) {
return  baseDao.findOne(id) ;
}

public Page<T> findAll (Pageable pageable ) {
return baseDao.findAll(pageable) ;
}
public List<T> findAll () {
return baseDao.findAll() ;
}

}

//具体实现类

public class NewsService  extends BaseService<News>  {

@Override
@Resource("newsDao")   //这里不能为baseDao
public void setBaseDao(BaseDao<News> baseDao) {
// TODO Auto-generated method stub
super.setBaseDao(baseDao);
}

}

抱歉!评论已关闭.