It’s insanely easy to write an interceptor in EJB3. Here’s a tutorial/example code for an interceptor which collects statistics info around a method invocation.
import java.util.Collection;
import javax.interceptor.AroundInvoke;
import javax.interceptor.InvocationContext;
import org.apache.commons.lang.time.StopWatch;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
public class StatisticsInterceptor {
private static final Log log = LogFactory
.getLog(StatisticsInterceptor.class);
@AroundInvoke
@SuppressWarnings("unchecked")
public Object intercept(InvocationContext ctx) throws Exception {
StopWatch stopWatch = new StopWatch();
stopWatch.start();
Object result = ctx.proceed();
log.debug("Statistics for "
+ ctx.getMethod().getDeclaringClass().getSimpleName() + "."
+ ctx.getMethod().getName());
log.debug("\tTime = " + stopWatch);
if (result instanceof String) {
log.debug("\tValue returned = " + result);
}
if (result instanceof Collection) {
Collection col = (Collection) result;
log.debug("\tSize of collection returned = " + col.size());
}
return result;
}
}
The only place, this needs to be added is in ejb-jar.xml
<assembly-descriptor>
<interceptor-binding>
<ejb-name>*</ejb-name>
<interceptor-class>org.jboss.seam.ejb.SeamInterceptor</interceptor-class>
</interceptor-binding>
<interceptor-binding>
<ejb-name>*</ejb-name>
<interceptor-class>com.evergreen.asr.util.StatisticsInterceptor</interceptor-class>
</interceptor-binding>
</assembly-descriptor>
That’s it.
Post a Comment