如何使用Seam 3拦截EntityManager的方法?

时间:2011-11-21 14:22:23

标签: cdi entitymanager seam3

我正在尝试拦截 Seam 3 项目中persist的方法updatejavax.persistence.EntityManager

在我试图制作的微框架的先前版本(Seam 2)中,我使用org.hibernate.Interceptor的实现并在persistence.xml中声明它来完成此操作。

但我现在想要更像“CDI”的东西,现在我们处于JEE6环境中。

我希望在进入EntityManager.persist来电之前,会抛出一个事件@BeforeTrackablePersist。同样,我想在进入@BeforeTrackableUpdate电话之前抛出一个事件EntityManager.mergeTrackable是我的一些Entity可以实现的接口,以便在持久或合并之前被截获。

我正在使用Seam 3(3.1.0.Beta3)扩展持久性管理器:

public class EntityManagerHandler {
    @SuppressWarnings("unused")
    @ExtensionManaged
    @Produces
    @PersistenceUnit
    private EntityManagerFactory entityManagerFactory;
}

所以我做了一个javax.enterprise.inject.spi.Extension,尝试了很多方法来做到这一点:

public class TrackableExtension implements Extension {

    @Inject @BeforeTrackablePersisted
    private Event<Trackable> beforeTrackablePersistedEvent;

    @Inject @BeforeTrackableMerged
    private Event<Trackable> beforeTrackableMergedEvent;

    @SuppressWarnings("unchecked")
    public void processEntityManagerTarget(@Observes final ProcessInjectionTarget<EntityManager> event) {
        final InjectionTarget<EntityManager> injectionTarget = event.getInjectionTarget();
        final InjectionTarget<EntityManager> injectionTargetProxy = (InjectionTarget<EntityManager>) Proxy.newProxyInstance(event.getClass().getClassLoader(), new Class[] {InjectionTarget.class}, new InvocationHandler() {
            @Override
            public Object invoke(final Object proxy, final Method method, final Object[] args) throws Throwable {
                if ("produce".equals(method.getName())) {
                    final CreationalContext<EntityManager> ctx = (CreationalContext<EntityManager>) args[0];
                    final EntityManager entityManager = decorateEntityManager(injectionTarget, ctx);
                    return entityManager;
                } else {
                    return method.invoke(injectionTarget, args);
                }
            }
        });
        event.setInjectionTarget(injectionTargetProxy);
    }

    public void processEntityManagerType(@Observes final ProcessAnnotatedType<EntityManager> event) {
        final AnnotatedType<EntityManager> type = event.getAnnotatedType();
        final AnnotatedTypeBuilder<EntityManager> builder = new AnnotatedTypeBuilder<EntityManager>().readFromType(type);

        for (final AnnotatedMethod<? super EntityManager> method : type.getMethods()) {
            final String name = method.getJavaMember().getName();
            if (StringUtils.equals(name, "persist") || StringUtils.equals(name, "merge")) {
                builder.addToMethod(method, TrackableInterceptorBindingLiteral.INSTANCE);
            }
        }

        event.setAnnotatedType(builder.create());
    }

    public void processEntityManagerBean(@Observes final ProcessBean<EntityManager> event) {
        final AnnotatedType<EntityManager> annotatedType = (AnnotatedType<EntityManager>)event.getAnnotated();
//      not even called
    }

    public void processEntityManager(@Observes final ProcessProducer<?, EntityManager> processProducer) {
        processProducer.setProducer(decorate(processProducer.getProducer()));
    }

    private Producer<EntityManager> decorate(final Producer<EntityManager> producer) {
        return new Producer<EntityManager>() {
            @Override
            public EntityManager produce(final CreationalContext<EntityManager> ctx) {
                return decorateEntityManager(producer, ctx);
            }
            @Override
            public Set<InjectionPoint> getInjectionPoints() {
                return producer.getInjectionPoints();
            }
            @Override
            public void dispose(final EntityManager instance) {
                producer.dispose(instance);
            }
        };
    }

    private EntityManager decorateEntityManager(final Producer<EntityManager> producer, final CreationalContext<EntityManager> ctx) {
        final EntityManager entityManager = producer.produce(ctx);
        return (EntityManager) Proxy.newProxyInstance(entityManager.getClass().getClassLoader(), new Class[] {EntityManager.class}, new InvocationHandler() {
            @Override
            public Object invoke(final Object proxy, final Method method, final Object[] args) throws Throwable {
                final String methodName = method.getName();
                if (StringUtils.equals(methodName, "persist")) {
                    fireEventIfTrackable(beforeTrackablePersistedEvent, args[0]);
                } else if (StringUtils.equals(methodName, "merge")) {
                    fireEventIfTrackable(beforeTrackableMergedEvent, args[0]);
                }
                return method.invoke(entityManager, args);
            }

            private void fireEventIfTrackable(final Event<Trackable> event, final Object entity) {
                if (entity instanceof Trackable) {
                    event.fire(Reflections.<Trackable>cast(entity));
                }
            }
        });
    }
}

在所有观察者方法中,只调用第二个(processEntityManagerType(@Observes ProcessAnnotatedType<EntityManager>))!即使对方法persistmerge添加了绑定,我的拦截器也永远不会被调用(我当然使用beans.xml中的正确行启用了它,并启用了我的扩展services/javax.enterprise.inject.spi.Extension文件)。

我认为CDI简单的东西实际上看起来真的很难......或者Seam 3可能会阻止这些代码正确执行......

有人知道如何处理吗?

2 个答案:

答案 0 :(得分:1)

我认为你让它变得比它需要的更难。首先,JPA和CDI集成在Java EE 6中并不是很好,我们非常希望Java EE 7和JPA 2.1中的更改​​。

您要做的是为EntityManager创建自己的生产者,该生产者将委托给EntityManager的实际实例,但是在调用您感兴趣的方法时也会触发自己的事件。看看Seam Persistence源代码可以看到一种方法。

答案 1 :(得分:0)

最后,我在SEAMPERSIST-75中应用了Seam Persistence的小补丁,理论上可以通过扩展org.jboss.seam.persistence.HibernatePersistenceProvider并覆盖方法proxyEntityManager(EntityManager)来实现。