我想建立一个@ApplicationScoped缓存机制,它基本上只存储它在启动时读取的一些数据库值。是否可以在不保持EntityManager和其他注入依赖项(即查询工厂)的情况下始终执行此操作?我只是在初始化期间需要它们。
答案 0 :(得分:1)
我不确定容器是否真的保持连接打开。但是我们会说它会。首先,你需要通过CDI注射EntityManager
。你可以这样做:
@ApplicationScoped
public class EntityManagerProducer {
@Produces
@PersistenceContext(unitName = "my-pu-name")
private EntityManager em;
}
然后在您的初始化方法中,您可以使用:
public void init() {
EntityManager entityManager = CDI.current().select(EntityManager.class).get();
// Do some stuff here
CDI.current().select(Entitymanager.class).destroy(entityManager);
}
.destroy
应确保依赖 不再有效。