Using EJB Interceptors — Part 1

EJBs provide the ability to intercept method calls to perform some common logic to all method calls like logging, or security checks. Three types of interceptors may be used: around-invoke interceptors, business method interceptors and lifecycle callback interceptors. In this post we only mention around-invoke interceptors.

To use around-invoke interceptors we use the @AroundInvoke annotation. The interceptor method has to use the signature:
Object method_name (InvocationContext ic) throws Exception;
This method can have public, private, protected, or package-level access, however it can not be static or final. The InvocationContext parameter is used for accessing the invocation chain. The invocation context provides several methods for accessing the called method, the called bean instance, and the parameters that will be used for the method call. Please see [1] for the details of the InvocationContext class.

Here is a sample interceptor logging the business method calls:

@AroundInvoke
    private Object logCalls(InvocationContext ic) throws Exception {
        logger.info("Processing call " + ic.getMethod().getName() +
                      "@" + ic.getTarget().toString());
        Object[] params = ic.getParameters();
        for (Object o : params) {
            logger.info("=>" + o.toString());
        }
        try {
            return ic.proceed();
        } finally {
            logger.info("Done with " + ic.getMethod().getName()
                     + "@" + ic.getTarget().toString());

        }
    }

The method logs the called method name and the instance name, then it logs the parameters of the call and finally it logs the called method and instance. It returns ic.proceed() to proceed to the next interceptor in the chain.

The output of this interceptor is below:

[#|intercepting method call|#]
[#|Processing call calculate@com.sirius.test.SimpleSessionBean@f3a7d9|#]
[#|=>1.0|#]
[#|=>2.0|#]
[#|Done with calculate@com.sirius.test.SimpleSessionBean@f3a7d9|#]

You can download the source code for the EJB and the test client here. We use the same stateless session bean sample from the previous EJB post.

References
1. http://java.sun.com/javaee/6/docs/api/javax/interceptor/InvocationContext.html

  • Share/Bookmark

About this entry