解决SSh中公共Dao使用泛型且Dao层无其他Dao,Service直接继承公共Dao,部署到tomcat可能会出现的错误。

来源:互联网 发布:ai软件下载最新版 编辑:程序博客网 时间:2024/05/22 13:43

org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'commonDao' defined in file......

Instantiation of bean failed; nested exception is org.springframework.beans.BeanInstantiationException: Could not instantiate bean class [com.zhangts.registration.dao.impl.UserDaoImpl]: Constructor threw exception; nested exception is java.lang.ClassCastException: java.lang.Class cannot be cast to java.lang.reflect.ParameterizedType


其实会犯这个错误是在CommondDaoImpl<T> extends HibernateDaoSupport implements CommonDao<T>中出现类似需要load对象的方法,比如 

public void deleteObjectByIDs(Serializable... ids){

for(int i=0;ids!=null && i<ids.length;i++){
Serializable id = ids[i];
Object object = (Object)this.getHibernateTemplate().get(entity, id);
this.getHibernateTemplate().delete(object);
}
}

实现这个方法里面,get方法需要entity.class,而这个class需要我们去转化,一般是这样去

private Class entity = (Class)GenericSuperClass.getClass(this.getClass());

GenericSuperClass这个类我们写在..util层

public class GenericSuperClass {

public static Class getClass(Class tClass) {
ParameterizedType pt = (ParameterizedType) tClass.getGenericSuperclass();
Class entity = (Class)pt.getActualTypeArguments()[0];
return entity;
}

}

这么一个项目部署在tomcat上就会报上面的错误信息。原因是在这句代码里

ParameterizedType pt = (ParameterizedType) tClass.getGenericSuperclass();

无法将java.lang.class强制转化为泛型。所以出错。


解决办法:

1. 公共Dao不使用泛型,使用  public void delete(final Object model);

2. 公共Dao使用泛型,但是需要写子Dao,每个表对应一个,该子Dao去继承这个CommonDao,就可以解决问题了(这个子Dao的内容可以是空的)

3. 只有公共Dao且使用泛型,那么将类似需要load对象的方法改写成这种样子:public T findObjectByID(Class<T> entity,Serializable id) 

这样就不会出错了

0 0
原创粉丝点击