EJB Timing with Interceptors

May 13, 2015
1 minute read

Java EE is packed tight with useful functionality. The humble Interceptor provides cross cutting functionality external to the targetted code, without modifying the code itself. In other words AOP. The API is rather simple an involves using @AroundInvoke.

The following highlights just how simple it is to log all EJB service call execution times, without the need to modify a single bean.

packagenet.bencode.common;importjavax.interceptor.AroundInvoke;importjavax.interceptor.InvocationContext;importorg.slf4j.Logger;importorg.slf4j.LoggerFactory;publicclassServicePerformanceInterceptor{privatestaticLoggerlogger=LoggerFactory.getLogger("timings");@AroundInvokepublicObjectcallLog(InvocationContextctx)throwsException{StringmethodName=ctx.getMethod().getName();StringclassName=ctx.getTarget().getClass().getName();longstartTime=System.currentTimeMillis();Objectresult=null;try{result=ctx.proceed();}finally{logger.debug("##### Total Execution Time Of "+methodName+" Is "+(System.currentTimeMillis()-startTime)+"MS"+" within "+className);}returnresult;}}