The @AroundInvoke annotation establishes the operations that an interceptor executes when the bean is intercepted. Here is a sample of an annotated operation for an interceptor:
@AroundInvoke
public Object aroundInvoke(InvocationContext ic) throws Exception {
String methodName = ic.getMethod().getName();
return ic.proceed();
}
To associate this interceptor to a bean, create a qualifier annotation:
@Retention(RUNTIME)
@Target({ METHOD, TYPE, CONSTRUCTOR })
@InterceptorBinding
public @interface Audit {
}
Add it on to the interceptor to identify the interceptor:
@Interceptor
@Audit
public class AuditInterceptor {
...}
And, at the end, add the qualifier in the method or field of the bean you want intercept:
@Audit
public List<Item> getList() {
return items;
}
Now when the getList() method is invoked, automatically the method of the Interceptor marked as @AroundInvoke is invoked.
In the case of Timeout method interceptors, the interceptor applies to all Timeout methods of the target class:
@AroundTimeout
public Object aroundTimeout(InvocationContext ic) throws Exception {
Object[] parameters = (Object[]) ic.getParameters();
return ic.proceed();
}
To execute this method of the interceptor, we need a bean marked as EJB working with the time service. It will be seen in detail in Chapter 4, Implementing Business logic.
A new invocation method of the interceptor introduced in Java EE 7 is the invocation through constructor:
@AroundConstruct
public Object aroundConstruct(InvocationContext ic) throws Exception {
Map<String, Object> data = ic.getContextData();
data.forEach((k, v) -> logger.info("data key: " + k + " - value: " + v));
return ic.proceed();
}
To start it, simply add the qualifier annotation in a constructor of a bean:
public class ItemServiceBean ...{
@Audit
public ItemServiceBean() {
items = new ArrayList<Item>();
}
...
}
We can exclude the invocation of class-level interceptors through the ExcludedInterceptors.class annotation or through deployment descriptors different by beans.xml. An example of a descriptor is the ejb-jar.xml that lets us exclude default and class interceptors.
Here's a sample of exclusion of class interceptors through annotation:
@interceptors({ ExcludedInterceptor.class, IncludedInterceptor.class })
public class SimpleService {
private Item item;
@ExcludeClassInterceptors
public Item getItem() {
return item;
}
public void setItem(Item item) {
this.item = item;
}
}
The getItem method will never be intercepted by ExcludedInterceptor and IncludedInterceptor, while setItem will be intercepted by both.