Jersey + HK2 + Grizzly:注入EntityManager的正确方法? [英] Jersey + HK2 + Grizzly: Proper way to inject EntityManager?

查看:51
本文介绍了Jersey + HK2 + Grizzly:注入EntityManager的正确方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经设法在 Jersey、HK2 和一个普通的 GrizzlyServer 中设置了我自己的服务类的注入(到资源类中).(基本上遵循 这个例子.)

I've managed to set up injection (into resource classes) of my own service classes in Jersey, HK2 and a plain GrizzlyServer. (Basically followed this example.)

我现在很好奇将 JPA EntityManagers 注入到我的资源类中最好的方法是什么?(我目前正在考虑将一个请求作为一个工作单元).我目前正在探索的一种选择是通过以下方式使用 Factory<EntityManager>:

I'm now curious what the best is to inject JPA EntityManagers into my resource classes? (I'm currently considering one request as one unit of work). One option that I'm currently exploring is to use a Factory<EntityManager> in the following way:

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 方法从未被调用.

The problem is that the dispose-method is never invoked.

我的问题:

  1. 这是在 Jersey+HK2 中注入 EntityManagers 的正确方法吗?
  2. 如果是这样,我应该如何确保我的 EntityManager 正确关闭?

(我宁愿不依赖重量级容器或额外的依赖注入库来覆盖这个用例.)

(I'd rather not depend on heavy weight containers or an extra dependency-injection library just to cover this use case.)

推荐答案

代替 Factory<T>.dispose(T),注册可注入的 CloseableService 可能做大部分你想做的事.Closeable 适配器将是必需的.CloseableService closes() 退出请求范围时所有注册的资源.

In place of Factory<T>.dispose(T), registering with the injectable CloseableService may do most of what you want. A Closeable adapter will be required. CloseableService closes() all registered resources upon exiting the request scope.

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;
    }
}

这篇关于Jersey + HK2 + Grizzly:注入EntityManager的正确方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆