Java Reference
In-Depth Information
Creating interceptors
There is one more CDI feature worth mentioning here, the interceptors. Sometimes, ap-
plications contain logic and cross-cutting multiple layers; the most simple example is log-
ging. Under the Java EE platform, it can be achieved using interceptors. First, we need to
create a new annotation:
@InterceptorBinding [1]
@Target({ ElementType.METHOD, ElementType.TYPE })
public @interface Logged {
// empty
This annotation defines an interceptor binding. It can be used to specify methods that you
would like to intercept. The bindings can be used on types as well; in that case, every
method call on that type is intercepted. The most important part of this definition is the
@InterceptorBinding [1] annotation. Be sure to add it!
Then, we have to create the interceptor definition itself:
@Logged [1]
public class LoggingInterceptor implements Serializable {
@AroundInvoke [2]
public Object log(InvocationContext context) throws
Exception {
final Logger logger =
logger.infov("Executing method {0}",
return context.proceed() [3];
We start by stating that our class is @Interceptor and it will be using the interceptor
binding that we've defined earlier ( @Logged [1] ). Next, we create a method log that
Search WWH ::

Custom Search