| Java EE 7 SDK |
CDI Interceptors intercept on invocations and lifecycle events on an associated target class. An interceptor is a class whose methods are invoked when business methods on the target class are invoked and/or when lifecycle events such as calls that create/destroy the bean occur. Interceptors are typically used to implement cross-cutting concerns like logging, auditing, and profiling.
This sample illustrates how interceptors can be added to a CDI bean that mimics a shopping cart.
The demo uses a ShoppingServlet to add items to the cart. The cart itself
is injected as a CDI bean and has a class-level interceptor which ensures that
the interceptor is applied to all methods of the bean. The interceptor (LoggingInterceptorSimple) is enabled
in WEB-INF/beans.xml and prints the method name being invoked.
An alternative
interceptor implementation (commented out in beans.xml) is also available and
may be enabled instead of or in addition to the existing interceptor.
The code snippet below shows the definition of LoggingInterceptor.
The @AroundInvoke annotation (only one per interceptor) on a method
in the interceptor class ensures that this method is invoked around the
business method interception.
@LoggingInterceptor
@Interceptor
public class LoggingInterceptorSimple {
@AroundInvoke
public Object log(InvocationContext context) throws Exception {
System.out.println("LOG: " + context.getMethod());
return context.proceed();
}
}
Perform the following steps to build, deploy, and run the application:
app_dir is the sample application base directory: samples_install_dir/javaee7/cdi/interceptors.app_dir.run outcome.
mvn clean verify cargo:run
clean outcome to undeploy the sample application and to remove the temporary directories such as build and dist.
mvn clean
If you have problems when running the application, refer to the troubleshooting document.
Copyright © 1997-2013 Oracle and/or its affiliates. All rights reserved.