EntityManager 注入 - NullPointerException
在我的 Spring+JPA/Hibernate+Wicket 应用程序中,我有一个 QueryBuilder bean,我想在我的 DAO 之一中使用它,它在 Criteria API 的帮助下生成类型化查询:
@Service(value="inboxQueryBuilder")
public class InboxQueryBuilder {
@PersistenceContext
EntityManager em;
CriteriaBuilder cb;
public InboxQueryBuilder() {
cb = em.getCriteriaBuilder();
}
public TypedQuery<App> getQueryForApps(AppSearchObject aso) {
...
}
...
}
但是,当我运行该应用程序时,我得到一个 null行指针异常:
cb = em.getCriteriaBuilder();
即 EntityManager 没有被注入。你知道为什么吗?
另外,这种使用是否正确且线程安全,或者我应该为每个查询实例化我的 InboxQueryBuilder 吗?在这种情况下,我还应该注入 EntityManager 还是应该将其作为构造函数参数传递(InboxQueryBuilder 将为 DAO 中具有注入的 EntityManager 实例的每个查询进行实例化)?
In my Spring+JPA/Hibernate+Wicket app, I have a QueryBuilder bean that I want to use in one of my DAOs which generates a typed query with the help of Criteria API:
@Service(value="inboxQueryBuilder")
public class InboxQueryBuilder {
@PersistenceContext
EntityManager em;
CriteriaBuilder cb;
public InboxQueryBuilder() {
cb = em.getCriteriaBuilder();
}
public TypedQuery<App> getQueryForApps(AppSearchObject aso) {
...
}
...
}
However, when I run the app, I get a null pointer exception for line:
cb = em.getCriteriaBuilder();
i.e. the EntityManager doesn't get injected. Do you know why?
Also, is this use correct and thread-safe or should I instantiate my InboxQueryBuilder for each query? In that case, should I also inject the EntityManager or should I just pass it as a constructor parameter (the InboxQueryBuilder would get instantiated for each query in the DAO which has an injected instance of EntityManager)?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您无法在构造函数中访问 EntityManager。看看@PostConstruct-Annotation
编辑:
再次阅读您的文章后,我开始不确定我是否正确。我知道 JBoss 中的 Java EE 依赖注入按照我所描述的方式工作,但我不确定 spring-IOC。
You can't access the EntityManager within the constructor. Take a look at the @PostConstruct-Annotation
EDIT:
After reading your post again, I start to became unsure, if I'm right. I know the Java EE-Dependency-Injection within a JBoss works as I described, but I'm not sure about spring-IOC.
您的应用程序上下文中是否有此 bean?
Do you have this bean somewhere in your application context?
Spring 使用 Java Beans 机制,所以我很确定这是不够的:
这是标准方法:
Spring uses the Java Beans mechanism, so I am pretty sure this is insufficient:
Here's the standard way: