Generic interceptors

Both transaction and security services can be considered runtime interceptors managed by the container. The container intercepts the method calls from the EJB stub and applies transaction context or security constraints around the calls.

In EJB 3.0, you can extend the container services by writing your own interceptors. Using the @AroundInvoke annotation, you can specify any bean method as the interceptor method that will execute before and after any other bean method runs. In the following example, the log() method is the interceptor that profiles and logs the execution time of other bean methods:


@Stateful
public class CalculatorBean implements Calculator {

// Bean methods that are to be intercepted by "log()"
// ... ...

@AroundInvoke
public Object log (InvocationContext ctx)
throws Exception {

String className = ctx.getBean().getClass().getName();
String methodName = ctx.getMethod().getName();
String target = className + "." + methodName + "()";

long start = System.currentTimeMillis();
System.out.println ("Invoking " + target);
try {
return ctx.proceed();
} catch(Exception e) {
throw e;
} finally {
System.out.println("Exiting " + target);

cal.setTrace(cal.getTrace() + "
" +
"Exiting " + target);
long time = System.currentTimeMillis() - start;
System.out.println("This method takes " +
time + "ms to execute");
}
}
}