a class to intercept in (that occur in an associated target class)
method invocations, or
lifecycle events
usage scope: on all managed objects of all kinds
declare and invoke order:
annotate with both @Interceptor and the @interceptor-binding-type (see below)
Either (if @Priority used, no need to specify in beans.xml)
be specified in beans.xml <interceptors><class>....</class></interceptors> (classes in same archive) and interceptors are invoked in the order specified in beans.xml, or
@Priority(Interceptor.Priority.XXX) specifies globally (smaller priority value called first)
intereptor method: can contain more than one, but no more than one of each type
@AroundInvoke
parameter: javax.interceptor.InvocationContext
returns: java.lang.object
throws: Exception
usually calls InvocationContext.proceed() method to invoke the method
@PostConstruct
@PreDestroy
@PrePassivate
@PostActive
@AroundTimeout - EJB timeout
annotations that associate interceptor with target beans or methods
javax.interceptor.@InterceptorBinding - mark for interceptor binding types
java.lang.annotation.@Inherited - subclasses inherit the annotation
Example interceptor binding type:
@Inherited
@InterceptorBinding
@Retention(RUNTIME)
@Target({METHOD, TYPE})
public @interface Logged {}
Annotate the bean (then on all methods of the bean) and individual methods (on specific methods) with the binding type to specify the interceptor to be invoked.
Annotation
@Inherited @InterceptorBinding @Retention(RUNTIME) @Target({METHOD, TYPE}) public @interface Logged { }
Usage
@Logged @SessionScoped public class PaymentHandler implements Serializable {...}
@Logged public String pay() {...} @Logged public void reset() {...}
Interceptor class implementation
@Logged @Interceptor @Priority(Interceptor.Priority.APPLICATION) public class LoggedInterceptor implements Serializable { ... }
(if @Priority not used, must specify in beans.xml)
Interceptor method
@AroundInvoke public Object modifyGreeting(InvocationContext ctx) throws Exception { Object[] parameters = ctx.getParameters(); String param = (String) parameters[0]; param = param.toLowerCase(); parameters[0] = param; ctx.setParameters(parameters); try { return ctx.proceed(); } catch (Exception e) { logger.warning("Error calling ctx.proceed in modifyGreeting()"); return null; } }