Simplest Possible EJB 3.1 Interceptor 📎
public class CallTracer {
@AroundInvoke
public Object transformReturn(InvocationContext context) throws Exception{
System.out.println("---" + context.getMethod());
return context.proceed();
}
}
You can apply the interceptor now on the EJB class or its methods. The simplest way is to use annotations - but you can use XML as well.
@Stateless
@Interceptors(CallTracer.class)
public class HelloBean{
public String sayHello(String message) {
return "Echo from bean: " + message;
}
}
How to compile:
You will need the the EJB 3.0 / 3.1 API in the classpath, or at least the @Interceptor annotation.
How to deploy:
Just JAR or WAR the interceptor with an EJB and put the archive into e.g: [glassfishv3]\glassfish\domains\domain1\autodeploy
Btw. the deployment of the WAR took on my machine:
INFO: Loading application LeanestInterceptor at /LeanestInterceptor
INFO: Deployment of LeanestInterceptor done is 298 ms
How to use:
e.g.:
public class HelloInterceptor extends HttpServlet {
@EJB
private HelloBean helloBean;
//....
}
And: there is no XML, strange configuration, libraries, additional dependencies needed... EJB 3 interceptors will run on >10 appservers. You will find the whole executable project (tested with Netbeans 6.7 and Glassfish v3 preview) in: http://kenai.com/projects/javaee-patterns/ [project name: LeanestInterceptor].
[See also "Real World Java EE Patterns - Rethinking Best Practices", page 42]