In this tutorial we will learn how to Audit EJB 3 Invocation Trail with Interceptors .
EJB 3+ is capable of applying custom interceptors to the business methods of your session and message driven beans. EJB 3 interceptors take the form of methods annotated with the @javax.ejb.AroundInvoke
annotation & having following signature:
@javax.ejb.AroundInvoke
public Object (javax.ejb.InvocationContext ctx) throws java.lang.Exception
Either define an interceptor method
- in the EJB itself,
- or in a separate class
but remember that there can only be one interceptor method per class. We will use the separate class approach which is more maintainable.
Define Interceptor Method
public class EJB3InvocationAuditInterceptor { @Resource private EJBContext context; @AroundInvoke protected Object audit(InvocationContext ctx) throws Exception { Principal principal = context.getCallerPrincipal(); Logger.getLogger().info("Received a call from "+principal.getName()); if (userIsValid(principal)) { }else{ //TODO log & throw exception } return ctx.proceed(); } }
Apply Custom Interceptor on EJB
@Interceptors(EJB3InvocationAuditInterceptor.class) @Stateless public class AuditedEJB3Bean { // TODO: your EJB3 Bean content }
Deploy & Access EJB
Bingo! You should see
Received a call from ...