Tuesday, May 4, 2021

Using EJB Interceptors to execute code AFTER service method completes

In my previous post Using EJB Interceptors to add functionality to existing Beans, we saw how to use EJB3 Interceptors to add common concern features like logging, etc. to J2EE service methods.
In case you want to run any piece of code after each service method call, you can wrap the return context.proceed(); in a try-finally block and add the "after" code in the finally block as shown below:


package com.my.ejb.interceptors;

import javax.interceptor.AroundInvoke;
import javax.interceptor.InvocationContext;

public class MyInterceptor {

    @AroundInvoke
    public Object interceptorMethod(InvocationContext context) throws Exception {
    	try {
          System.out.println("Before invoking method: " + context.getMethod());
          return context.proceed();
        } finally {
          System.out.println("After invoking method: " + context.getMethod());
        }
    }
}

Once this interceptor is created, we just need to add an "@Interceptors" annotation to the target EJB as:

import javax.interceptor.Interceptors;

@Interceptors({com.my.ejb.interceptors.MyInterceptor.class})

Now you should see log lines "Before ..." before the the method executes and "After..." after the method executes!


No comments:

LinkWithin

Related Posts Plugin for WordPress, Blogger...