【发布时间】:2019-03-28 19:47:36
【问题描述】:
我知道我可以做到以下几点:
public class MyDao{
private EntityManager em;
public void setEm(EntityManager em){
this.em = em;
}
...
然后,使用@PostConstuct 传递EntityManager
public class MyBean{
private EntityManager em;
@Inject
private MyDao myDao;
@PostConstruct
private void init(){
myDao.setEm(em);
}
...
但是由于我的应用程序的架构限制,我不能直接将 MyDao 注入 MyBean,我应该通过 MyBusinessDao 类,所以我尝试了以下方法,但我在 MyDao 中获得了 EntityManager 值上的 nullPointerExeception :
public class MyBean{
private EntityManager em;
public MyBean(){
em = createEntityManager();
}
private EntityManager createEntityManager(){
//dynamically create the EntityManager
}
@Inject
private MyBusinessDao myBusinessDao;
@PostConstruct
private void init(){
myBusinessDao.setEm(em);
}
...
我在 MyBusinessDao 中注入 MyDao:
public class MyBusinessDao {
private EntityManager em;
@Inject
private MyDao myDao;
@PostConstruct
private void init(){
myDao.setEm(em);
}
...
我应该提到我没有使用J2EE 容器
【问题讨论】:
-
只需在你真正需要的地方声明 em,并用
@PersistenceContext注释它。为什么要在不需要的地方注入它,然后尝试将其传递给其他 bean? -
@JBNizet 感谢您的回答,事实上,所有(业务、doa 和实体)类都将打包在一个 jar 中并由另一个团队使用,该团队将提供自己的 entityManager,这就是为什么它应该是上级声明
-
不,不应该。豆子就是豆子。
-
您能否建议我另一种将
EntityManager从我的 Bean 传递到 Dao 的方法 -
正如我所说,不要。将其注入您需要的地方。 DAO 是一个 bean,它存在于 EntityManager 可用的应用程序中,因此 EM 将被注入 DAO。