【发布时间】:2012-05-22 07:37:00
【问题描述】:
目前VariableService 在我的控制器中是@Autowired。
我意识到我可以实现类ParameterizedType 来消除这个错误,但我担心我可能会走错方向。有没有更好的方法来做到这一点,还是我需要硬着头皮实施ParameterizedType的方法?
org.springframework.beans.factory.BeanCreationException:创建名为“contentController”的bean时出错:注入自动装配依赖项失败;嵌套异常是 org.springframework.beans.factory.BeanCreationException:无法自动装配字段:私有 com.fettergroup.cmt.service.VariableService com.fettergroup.cmt.web.ContentController.variableService;嵌套异常是 org.springframework.beans.factory.BeanCreationException:在 ServletContext 资源 [/WEB-INF/dispatcher-servlet.xml] 中定义名称为“variableService”的 bean 创建时出错:bean 的实例化失败;嵌套异常是 org.springframework.beans.BeanInstantiationException:无法实例化 bean 类 [com.fettergroup.cmt.service.VariableService]:构造函数抛出异常;嵌套异常是 java.lang.ClassCastException: java.lang.Class cannot be cast to java.lang.reflect.ParameterizedType
变量服务
public class VariableService extends EntityService {
public VariableService () {
super.setEntityRepository(new VariableRepository());
}
}
实体服务
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;
}
}
【问题讨论】:
标签: java spring-mvc