Wednesday, May 9, 2012

InterceptorBinding in 4 Steps for CDI/JEE6 applications

Interceptors with interceptor binding in CDI/JEE6 enabled applications can be written & used by following the below simple steps.

  1. Create a custom annotation with @InterceptorBinding 
    @Inherited
    @InterceptorBinding
    @Retention (RetentionPolicy.RUNTIME)
    @Target ({ElementType.METHOD, ElementType.TYPE})
    public @interface Logged {
       
    }
  2. Create an interceptor class & annotate the class with the custom annotation. 
    @Logged
    @Interceptor
    public class LoggingInterceptor {
  3. add a method to the interceptor. Annotate the method with @AroundInvoke annotation & pass InvocationContext object as a parameter.
    @AroundInvoke
    public Object logMethodEntry(InvocationContext invocationContext)
  4. Specify the interceptor in beans.xml file. 

Now, the interceptor is ready to be used via the custom annotation. Use the custom annotation created earlier in the methods of the service classes those are exposed via CDI. (see below). This will make the CDI container to invoke the interceptor's intercepting method ( this is the method which is present in the Interceptor class & annotated with @AroundInvoke ) .

@Logged
public String greet( final String greeter ){
   return "Hallo " + greeter + " from EJB";
} The complete code can be found here. Please see the video below, where I have demonstrated uses of Interceptors.


1 comment: