Jersey + HK2 + Grizzly: Proper way to inject EntityManager?

前端 未结 1 874
南旧
南旧 2020-12-30 12:35

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.)

I\'m

相关标签:
1条回答
  • 2020-12-30 13:13

    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;
        }
    }
    
    0 讨论(0)
提交回复
热议问题