# Interceptors in EJB

In 
Published 2022-12-03

This tutorial explains to you what an interceptor in EJB is.

EJB 3.0 provides specification to intercept business methods calls using methods annotated with @AroundInvoke annotation.

Interceptors, as the name states, are components that intercepts calls to EJB methods. The Interceptors intercept the call to the EJB and do something before the EJB method calls. After an EJB method call could be done in the EJB if you want to do an "after call". The Interceptors may be used for instance to implement an auditing or logging system around the calls to EJB.

Here is an example of creating/ using EJB in Java :

AddIntegers.java
package ejb;
 
import javax.ejb.Stateless;
import javax.interceptor.Interceptors;
 
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
 
@Stateless(mappedName="/AddIntegers")
@Interceptors ({MyInterceptor.class})
public class AddIntegers implements AddIntegersRemoteInterface {
     
    private static final Logger logger = LoggerFactory.getLogger(AddIntegers.class);
     
    @Override
    public int returnSuma(int a, int b) {
        // What the EJB3 will return
        System.out.println("returnSuma() call");
        logger.error("before return in AddIntegers > IN : AddIntegers " );
        return a+b;
    }
}
MyInterceptor.java
package ejb;
 
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
 
    import javax.interceptor.AroundInvoke;
    import javax.interceptor.InvocationContext;
 
    public class MyInterceptor {
         
      private static final Logger logger = LoggerFactory.getLogger(MyInterceptor.class);
         
       @AroundInvoke
       public Object methodInterceptor(InvocationContext ctx) throws Exception
       {
          System.out.println("*** Intercepting call to AddIntegers methods: "
          + ctx.getMethod().getName());
           
          logger.error("@AroundInvoke : before return > IN: "+ ctx.getMethod().getName());
           
          return ctx.proceed();
       }
    }

And here is the result when the EJB is called :

For seeing these messages you can take a look into the log file of the WebLogic server as well.