目前VariableService
在@Autowired
我的控制器中。
我意识到我可以实现这个类ParameterizedType
来消除这个错误,但我担心我可能会走错方向。有没有更好的方法来做到这一点,还是我需要硬着头皮实施ParameterizedType
's 方法?
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 不能强制转换为 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 {
}
实体库
@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;
}
}