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.
Nice, perhaps a better link to the javax.interceptor package:
ReplyDeletehttp://svn.apache.org/repos/asf/geronimo/specs/trunk/geronimo-interceptor_1.1_spec/src/main/java/javax/interceptor/
Shouldn't annotation be called LogTime intead of Log in step 1?
ReplyDelete