Default Interceptors in CDI Beans

1000 views Asked by At

I have a question. Whenever we have EJB jars

<ejb-jar
   xmlns = "http://java.sun.com/xml/ns/javaee"
   version = "3.0"
   xmlns:xsi = "http://www.w3.org/2001/XMLSchema-instance"
   xsi:schemaLocation = "http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/ejb-jar_3_0.xsd"
        >
    <interceptors>
        <interceptor>
            <interceptor-class>net.bull.javamelody.MonitoringInterceptor</interceptor-class>
        </interceptor>
    </interceptors>
    <assembly-descriptor>
        <interceptor-binding>
            <ejb-name>*</ejb-name>
            <interceptor-class>net.bull.javamelody.MonitoringInterceptor</interceptor-class>
        </interceptor-binding>
    </assembly-descriptor>
</ejb-jar>

Now my MonitoringInterceptor Intercept all EJBs. Here comes a question: can I do something similar with CDI Interceptors?

<beans xmlns="http://java.sun.com/xml/ns/javaee"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="
      http://java.sun.com/xml/ns/javaee
      http://java.sun.com/xml/ns/javaee/beans_1_0.xsd">
    <interceptors>
        <class>net.bull.javamelody.MonitoringInterceptor</class>
    </interceptors>

</beans>

I would like to have MonitoringInterceptor set by default to all CDI Beans injected to application. How can I acquire that?

2

There are 2 answers

3
aschoerk On BEST ANSWER

I don't think there is a declarative way to do it - with good reason as "all beans" is a rather vague concept in the world of CDI. Beans come and go even after deployment time. This article describes a way to do it programmatically for all beans which are registered with the manager, which will possibly net you your desired result: byteslounge.com/tutorials/…

0
aschoerk On

A way would be to create an Extension that adds the Annotation to the classes.

As practical example you can look at EjbExtensionExtended

processAnnotatedType(@Observes ProcessAnnotatedType<T> pat) 

makes sure that the beans can be handled

createEJBWrapper 

adds @EjbTransactional to the class if necessary.