
Interceptor bindings
Interceptors can intercept any bean except other interceptors. To transform a bean in an interceptor, simply add the @Interceptor annotation to the bean:
@Interceptor
@Logging
@Priority(LIBRARY_BEFORE)
public class LoggingInterceptor {
@Inject
@Intercepted
private Bean<?> bean;
@AroundInvoke
public Object aroundInvoke(InvocationContext ic) throws Exception {...}
An interceptor binding is a Java annotation annotated with the @InterceptorBinding. An interceptor binding of a bean can be declared as bean class level, or a method level of the bean class, through this annotation or with a stereotype that declares the interceptor binding. Here is a sample:
@Retention(RUNTIME)
@Target({ METHOD, TYPE, CONSTRUCTOR })
@InterceptorBinding
public @interface Logging {
}
In the following example, LoggingInterceptor will be applied at the class level and therefore applies to all business methods of the class:
@Logging
public class SimpleService {...}
Alternatively, we can use the interceptors annotation:
@interceptors({ ExcludedInterceptor.class, IncludedInterceptor.class })
public class SimpleService {...}
In this example, the LoggingInterceptor will be applied at the method level:
public class ItemServiceBean implements ItemService {
@Logging
@Override
public void create(Item item) {
items.add(item);
}
...}
A new feature from CDI 1.2 in Java EE 7 is the @Intercepted annotation. With it, an interceptor can trace the injected bean, read its metadata, and manipulate the bean. Here's an example of the programmatic execution of an injected bean:
@Inject
BeanManager beanManager
...
beanManager.getContext(bean.getScope()).get(bean, beanManager.createCreationalContext(bean));
In this case you need the BeanManager. It can be injected inside the interceptor. If a managed bean class is declared with the final construct, it cannot have any interceptor bindings. If it has a non-static, non-private, final method, it cannot have any class-level interceptor bindings, and no method-level interceptor bindings for its methods.