Monday, January 18, 2010

JSR-299 CDI Interceptors

Playing around with Java EE 6 these days, I came across some new features, I will blog about. Today I just want to give a short introduction to the enhancements made to javax.interceptor by the CDI.

Interceptor functionality is allready defined by the Java Interceptors specification. CDI enhances this with a more sophisticated, annotation-based approach for binding interceptors to beans. Only four stepts to get to your new CDI interceptor.

1) Write the interceptor binding:

@InterceptorBinding
@Target({METHOD, TYPE})
@Retention(RUNTIME)
public @interface Log {}


2) Write the interceptor:

@LogTime
@Interceptor
public class LoggingInterceptor {

@AroundInvoke
public Object logExecutionTime(InvocationContext ic) throws Exception {
long start = System.currentTimeMillis();
try {
return ic.proceed();
} catch (Exception e) {
throw e;
} finally {
long time = System.currentTimeMillis() - start;
String method = ic.getClass().getName();
Logger.getLogger(
LoggingInterceptor.class.getName())
.log(Level.INFO, "*** Invocation of "
+ method + " took " + time + "ms");
}
}
}


3) Declare the interceptor in beans.xml:
<interceptors>
<class>cdi.LoggingInterceptor</class>
</interceptors>

4) Use the interceptor in your code:

//...
@LogTime
public String getText() {
//..
}


That is all. Have fun.