目前VariableService
被@Autowired
在我的控制器。
我知道我可以实现类ParameterizedType
使这个错误消失,但我担心,我会在错误的方向前进。 有没有更好的办法做到这一点还是需要咬紧牙关和实施ParameterizedType
的方法呢?
org.springframework.beans.factory.BeanCreationException:错误创建名为“contentController”豆:自动装配Autowired依赖注入失败; 嵌套的例外是org.springframework.beans.factory.BeanCreationException:无法自动装配领域:私人com.fettergroup.cmt.service.VariableService com.fettergroup.cmt.web.ContentController.variableService; 嵌套异常是org.springframework.beans.factory.BeanCreationException:错误创建具有名称豆“variableService”在ServletContext的资源定义[/WEB-INF/dispatcher-servlet.xml]:bean的实例化失败; 嵌套异常是org.springframework.beans.BeanInstantiationException:无法实例bean类[com.fettergroup.cmt.service.VariableService]:构造抛出异常; 嵌套的例外是java.lang.ClassCastException:java.lang.Class中不能转换为java.lang.reflect.ParameterizedType
可变服务
public class VariableService extends EntityService {
public VariableService () {
super.setEntityRepository(new VariableRepository());
}
}
EntityService
public abstract class EntityService<T> {
public EntityRepository<T> entityRepository;
public T create(T entity) {
return entityRepository.create(entity);
}
public T update(T entity) {
return entityRepository.update(entity);
}
public void delete(T entity) {
entityRepository.delete(entity);
}
public void setEntityRepository(EntityRepository<T> entityRepository) {
this.entityRepository = entityRepository;
}
}
可变信息库
public class VariableRepository extends EntityRepository {
}
EntityRepository
@Repository
public abstract class EntityRepository<T> {
//the equivalent of User.class
protected Class<T> entityClass;
@PersistenceContext(type= PersistenceContextType.TRANSACTION)
public EntityManager entityManager;
public EntityRepository () {
//Get "T" and assign it to this.entityClass
ParameterizedType genericSuperclass = (ParameterizedType) getClass().getGenericSuperclass();
this.entityClass = (Class<T>) genericSuperclass.getActualTypeArguments()[0];
}
/**
* Create this entity
* @param t
* @return
*/
public T create(T t) {
entityManager.persist(t);
return t;
}
/**
* Update this entity
* @param t
* @return
*/
public T update(T t) {
return entityManager.merge(t);
}
/**
* Delete this entity
* @param entity
*/
public void delete(T t) {
t = this.update(t);
entityManager.remove(t);
}
public void setEntityManager(EntityManager entityManager) {
this.entityManager = entityManager;
}
}