adam bien's blog

Simplest Possible EJB 3.1 Interceptor - If You Love XML 📎

Annotations are great, but sometimes it is necessary to disable an interceptor without being forced to recompile your code. In EJB 3.0/1 you can completely get rid off annotations and configure everything in XML (what was awesome in 2000 :-)). The XML-configuration is very similar to the declaration of Servlet-Filters: you have to declare the Interceptor first, and then you can associate it with an EJB 3.1:

<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>com.abien.samples.interceptors.PerformanceMeasurement</interceptor-class>
        </interceptor>
    </interceptors>
    <assembly-descriptor>
        <interceptor-binding>
            <ejb-name>HelloBean</ejb-name>
            <interceptor-order>
                <interceptor-class>com.abien.samples.interceptors.PerformanceMeasurement</interceptor-class>
            </interceptor-order>
        </interceptor-binding>
    </assembly-descriptor>
</ejb-jar>

The EJB comes without the @Interceptors tag. The XML configuration would override it anyway. This behavior is useful and generally applied in EJB 3 - land. You can override annotations with XML, what is especially interesting for testing.

@Stateless
public class HelloBean implements Hello {

    public String sayHello() {
        return "Hello from Session Bean";
    }
}
...and the interceptor knows nothing about XML:

public class PerformanceMeasurement {

    @AroundInvoke
    public Object trace(InvocationContext invocationContext) throws Exception{
        long start = System.nanoTime();
        try{
            return invocationContext.proceed();
        }finally{
            long executionTime = (System.nanoTime() - start);
            System.out.println("Method: " + invocationContext.getMethod() + " executed in: " + executionTime + " ns");
        }
    }
}

You will find the whole project in:http://kenai.com/projects/javaee-patterns/.

[I used the sample to explain some EJB 3.1/3.0 principles in the "Real World Java EE Patterns" book as well.]