我已经成功地在 Jersey、HK2 和一个普通的 GrizzlyServer 中设置了我自己的服务类的注入(到资源类中)。 (基本上遵循这个例子.)
我现在很好奇将 JPA EntityManager 注入我的资源类中最好的方法是什么? (我目前正在考虑将一个请求作为一个工作单元)。我目前正在探索的一个选择是使用Factory<EntityManager>
通过以下方式:
class MyEntityManagerFactory implements Factory<EntityManager> {
EntityManagerFactory emf;
public MyEntityManagerFactory() {
emf = Persistence.createEntityManagerFactory("manager1");
}
@Override
public void dispose(EntityManager em) {
em.close();
}
@Override
public EntityManager provide() {
return emf.createEntityManager();
}
}
并按如下方式绑定:
bindFactory(new MyEntityManagerFactory())
.to(EntityManager.class)
.in(RequestScoped.class);
问题是dispose
- 方法从未被调用。
我的问题:
- 这是在 Jersey+HK2 中注入 EntityManager 的正确方法吗?
- 如果是这样,我应该如何确保我的 EntityManager 正确关闭?
(我宁愿不依赖重量级容器或额外的依赖注入库来覆盖这个用例。)
代替Factory<T>.dispose(T)
,用注射剂注册CloseableService
可能会做大部分你想做的事。 ACloseable
需要适配器。CloseableService
closes()
退出请求范围时的所有注册资源。
class MyEntityManagerFactory implements Factory<EntityManager> {
private final CloseableService closeableService;
EntityManagerFactory emf;
@Inject
public MyEntityManagerFactory(CloseableService closeableService) {
this.closeableService = checkNotNull(closeableService);
emf = Persistence.createEntityManagerFactory("manager1");
}
@Override
public void dispose(EntityManager em) {
em.close();
}
@Override
public EntityManager provide() {
final EntityManager em = emf.createEntityManager();
closeableService.add(new Closeable() {
public final void close() {
em.close();
}
});
return em;
}
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)