我知道我可以做到以下几点:
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类,所以我尝试了以下但我得到了nullPointerExeception
在myDao的EntityManager
值:
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
容器
您可以实现CDI生产者方法,以通过CDI注入提供EntityManager。
@ApplicationScoped
class EntityManagerProducer {
@PersistenceContext(...)
private EntityManager em;
@Produces
@RequestScoped
public EntityManager produceEm() {
return em;
}
}
您还可以注入EntityManagerFactory并在producer方法中调用emf.createEntityManager()并实现CDI-Disposer方法,该方法在范围完成之前关闭EntityManager。
public void dispose(@Disposes EntityManager em) { ... }
如果您有多个持久性上下文,则为每个持久性上下文实现一个生成器方法,并使用CDI-Qualifier对它们进行限定。
我这样解决了:
public class MyBusinessDao {
private EntityManager em;
@Inject
private MyDao myDao;
private void setEm(EntityManager em){
this.em = em;
//and here i call the setEm method of myDao also
myDao.setEm(em);
}
...