7

Jersey、HK2、およびプレーンな GrizzlyServer で、独自のサービス クラスの (リソース クラスへの) インジェクションを設定することができました。(基本的にはこの例に従います。)

リソース クラスに JPA EntityManagers を挿入するのに最適なものは何ですか? (現在、1回のリクエストを1単位として考えています)。私が現在検討している 1 つのオプションはFactory<EntityManager>、次の方法でa を使用することです。

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 に EntityManagers を注入するための正しいアプローチですか?
  2. その場合、EntityManagers が適切に閉じられていることを確認するにはどうすればよいですか?

(このユースケースをカバーするためだけに、重いコンテナや追加の依存性注入ライブラリに依存したくありません。)

4

1 に答える 1

6

の代わりにFactory<T>.dispose(T)、injectable に登録すると、必要なCloseableServiceことのほとんどが実行される場合があります。Closeableアダプターが必要になります 。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;
    }
}
于 2013-11-25T18:52:30.720 に答える