【问题标题】:Jersey + HK2 + Grizzly: Proper way to inject EntityManager?Jersey + HK2 + Grizzly:注入EntityManager的正确方法?
【发布时间】:2013-10-05 14:03:12
【问题描述】:

我已经设法在 Jersey、HK2 和一个普通的 GrizzlyServer 中设置了我自己的服务类的注入(到资源类中)。 (基本关注this example。)

我现在很好奇将 JPA EntityManagers 注入到我的资源类中最好的方法是什么? (我目前正在考虑将一个请求作为一个工作单元)。我目前正在探索的一种选择是通过以下方式使用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-方法从未被调用过。

我的问题:

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

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

【问题讨论】:

  • stackoverflow.com/questions/17396165/… 提出了类似的问题。
  • 是的。我已经对这个问题投了赞成票并发表了评论。
  • 我使用的是 Jersey 2.10.1,我没有这个问题。 dispose() 按预期调用。

标签: jpa dependency-injection jersey grizzly hk2


【解决方案1】:

代替Factory&lt;T&gt;.dispose(T),注册CloseableService 可以满足您的大部分需求。需要Closeable 适配器。 CloseableServicecloses()退出请求范围时所有注册的资源。

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-11-03
    • 1970-01-01
    • 1970-01-01
    • 2016-11-18
    • 2015-03-18
    • 2014-12-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多