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.]
Hi Adam,
you mentioned, that one can disable a "per-annotation" defined Interceptor in XML, but your example binds an interceptor to a bean too.
Could you provide an example that disables an interceptor via xml?
Thanks,
Robert
Posted by Robert on July 21, 2009 at 03:43 PM CEST #
Is it possible to define an "interceptor chain" composed of one or more interceptors and then bind this interceptor chain to a group of EJBs defined with a pattern, for instance "com.mycompany.myproject.*.*SessionBean"
Posted by Gérald on July 21, 2009 at 06:08 PM CEST #