【问题标题】:Spring pass entity to super classSpring将实体传递给超类
【发布时间】:2018-04-24 15:16:53
【问题描述】:

我已经创建了这样的通用超类:

@Repository
public class RootQueryCreator<T> {

   @PersistenceContext
   private EntityManager em;

   private T entity;
   CriteriaBuilder criteriaBuilder = null;
   CriteriaQuery<T> criteriaQuery = null;
   Root<T> rootTable = null;

   public RootQueryCreator() {}

   public RootQueryCreator(T entity) {
    super();
    this.entity = entity;
   }

   @PostConstruct
   public void initRootQuery() {
    criteriaBuilder = em.getCriteriaBuilder();
    criteriaQuery = (CriteriaQuery<T>) 
    criteriaBuilder.createQuery(this.entity.getClass());        
    rootTable = (Root<T>) criteriaQuery.from(entity.getClass());
}}

这个超类将被实体中的每个 DAOImpl-Class 使用。 像这样:

@Repository
@Qualifier("myEntitiyClass")
public class MyEntityDAOImpl  extends 
RootQueryCreator<MyEntity> { 

@Autowired
public MyEntityDAOImpl() {
    super(new MyEntity()); //pass any Entity for the Root-Class from Criteria-Framework
}

@Override
public List<MyEntity> getAll() throws Exception {
    super.getCriteriaQuery().select(super.rootTable);
    return super.getEm().createQuery(criteriaQuery).getResultList();
}

public List<MyEntity> retrieveData(){

}}  

每个 DAOImpl-Class 都会自动连接到一些服务类中,如下所示:

@Service
public class myLecture {

@Autowired
@Qualifier("myEntitiyClass")
private JpaRepositority<MyEntityDAOImpl> myEntityDAOImpl;

public void retrieveData(){

     myEntityDAOImpl.retrieveData();
} }

最后我得到了这个错误:

IllegalStateException: Autowired 注解至少需要一个 参数:MyEntityDAOImpl()

实际上我不需要将任何实体传递给 DAOImpl-Class。 我该怎么办?

【问题讨论】:

    标签: spring jpa-2.0 autowired


    【解决方案1】:

    Autowired 注释指定:

    将构造函数、字段、setter 方法或 config 方法标记为 由 Spring 的依赖注入工具自动装配。

    但是您使用 @Autowired 注释了构造函数,而没有提供任何依赖项作为参数:

    @Autowired
    public MyEntityDAOImpl() { //-> Empty arg is the issue here
        super(new MyEntity()); //pass any Entity for the Root-Class from Criteria-Framework
    }
    

    而例外:

    IllegalStateException: Autowired annotation 至少需要一个 参数:MyEntityDAOImpl()

    事实上,您不需要在MyEntityDAOImpl 中自动装配任何东西,因为它的构造函数中不需要任何依赖项。所以只需删除注释并让 Spring 将构造函数作为普通构造函数调用:

    public MyEntityDAOImpl() {
        super(new MyEntity()); //pass any Entity for the Root-Class from Criteria-Framework
    }
    

    【讨论】:

    • 谢谢。它似乎工作。另外我已经从超类中删除了@Repository-Annotation。因为在通过子类从超类实例化并将某些实体传递给超类之后,IoC-Container 开始再次将超类实例化为 bean。但是第二次我没有通过任何实体并获得空指针异常
    • 不客气。注释确实不是必需的,并且正如您所注意到的那样可能是有害的。另请注意,如果父类不是为了实例化而设计的,则它应该是抽象的。
    猜你喜欢
    • 1970-01-01
    • 2015-07-25
    • 2021-10-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-10-16
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多