January 9, 2015

The Java EE 6 Interceptors


The AOP Interceptor was in EE 6 introduced and was before only supported with additional libraries such as aspectj and jboss-aop.

Before using Interceptor one should first really consider if this is the right tool for solving ones problem. Because using AOP Interceptor is not a holy grail, BUT for certain problem it is. Those are:

  • Logging
  • Caching
  • Security
  • And similiar

The above examples are so called cross cutting concern, that are well suited to be solved with AOP Interceptor.

Java EE 6 Interceptors

To create a Java EE Interceptor you create a POJO with:

  • A public, no-argument constructor.
  • One around-invoke interceptor method with syntax @javax.interceptor.AroundInvoke visibility Object method-name(javax.interceptor.InvocationContext) throws Exception { ... }


To use it, add @javax.interceptor.Interceptors(AuditInterceptor.class) to any bean that supports injection, e.g. Servlet, JSF ManagedBean, EJB.


NOTE: You can either annotate the class (Interceptor will be called whenever every public method is called) or a specific method.

The final piece to make it work is to add the beans.xml in:

  • META-INF/ for ejb jar.
  • WEB-INF/ for web war.


Oracle EE 6 Tutorial Chapter 50: Using Java EE Interceptors

No comments: