To add any decorations or cross-cutting features like logging, profiling or performance measurement for service method calls of existing enterprise beans, you can use EJB3 Interceptors that were provided starting with JavaEE5.
Interceptor is a method that wraps around the invocation of the actual business method call allowing you to apply the required feature and can either exist in the target class if it is very speficic to that class; or in an external class if it applies to multiple service methods. If it is a part of an external class, then it has to be the only method in that class having the annotation "@AroundInvoke"
This interceptor method takes the following form:
package com.my.ejb.interceptors;
import javax.interceptor.AroundInvoke;
import javax.interceptor.InvocationContext;
public class MyInterceptor {
@AroundInvoke
public Object interceptorMethod(InvocationContext context) throws Exception {
System.out.println("Going to invoke method: " + context.getMethod());
return context.proceed();
}
}
Once this interceptor is created, we just need to add an "@Interceptors" annotation to the target EJB as:
@Interceptors({com.my.ejb.interceptors.MyInterceptor.class})And viola - it simply works, no need for any additionaly libraries or frameworks!
Note: Do not forget the return context.proceed(); call at the end of the interceptor method - this will allow the chain of interceptors to proceed and the target metod to be invoked!