NovatecConsulting / BeanTest

Bean Testing for Java EE Applications
http://blog.novatec-gmbh.de/unit-testing-jee-applications-cdi/
Apache License 2.0
25 stars 12 forks source link

Injection in EJB interceptors is not working #3

Open agori opened 10 years ago

agori commented 10 years ago

PersistenceContext is not injected in EJB interceptors, and throws NullPointerException when I try to access the EntityManager. This issue forces me to rewrite all the interceptors.

public class MyInterceptor {

    @PersistenceContext EntityManager em;

    @AroundInvoke
    public Object handle(InvocationContext context) throws Exception {
        try {
            return context.proceed();
        } finally {
            em.flush();  // throws NPE!
        }
    }
}
carlosbarragan commented 10 years ago

Thanks for creating the issue.

We will take care of it in the next release (0.2).

bbq2100 commented 10 years ago

At the moment I´am fixing the NPE :bug: in https://github.com/qabbasi/BeanTest/tree/Issue%233 :wink:

bbq2100 commented 10 years ago

Tried the following:

public void processAfterBeanDiscovery(@Observes AfterTypeDiscovery afterTypeDiscovery, BeanManager beanManager) { List<Class<?>> interceptors = afterTypeDiscovery.getInterceptors(); }

But AfterTypeDiscovery#getInterceptors returns an empty Interceptor list.

Ref: http://docs.oracle.com/javaee/7/api/javax/enterprise/inject/spi/AfterTypeDiscovery.html

bbq2100 commented 10 years ago

Alternative approach: retrieve via the @Interceptors(Class[]) annotation all old fashioned Interceptor definitions altogether with injection points such as the @PersistenceContext.

Old fashioned interceptorbinding

@Interceptors(MyInterceptor.class) public class MyInterceptedBean {}

Sample interceptor (without @InterceptorBinding)

public class MyInterceptor {

@PersistenceContext <-- replaced by @Inject
EntityManager em;

@AroundInvoke
public Object handle(InvocationContext context) throws Exception {
    try {
        return context.proceed();
    } finally {
        em.flush();
    }
}

}