JSR-299 CDI Interceptors

Markus Eisele
2
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.

Post a Comment

2Comments

  1. Nice, perhaps a better link to the javax.interceptor package:

    http://svn.apache.org/repos/asf/geronimo/specs/trunk/geronimo-interceptor_1.1_spec/src/main/java/javax/interceptor/

    ReplyDelete
  2. Shouldn't annotation be called LogTime intead of Log in step 1?

    ReplyDelete
Post a Comment