Java EE 7 SDK 

Samples Main Page

The Interceptors CDI Sample Application

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.

Description

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();
    }
}

Building, Deploying, and Running the Application

Perform the following steps to build, deploy, and run the application:

  1. Set up your build environment and configure the application server with which the build system has to work by following the common build instructions.
  2. app_dir is the sample application base directory: samples_install_dir/javaee7/cdi/interceptors.
  3. Change directory to app_dir.
  4. Build, deploy, and run the sample application using the run outcome.

    mvn clean verify cargo:run

  5. Use the clean outcome to undeploy the sample application and to remove the temporary directories such as build and dist.

    mvn clean

Troubleshooting

If you have problems when running the application, refer to the troubleshooting document.



Copyright © 1997-2013 Oracle and/or its affiliates. All rights reserved.