Java Reference
In-Depth Information
Servlet i lters are easy‐to‐implement tools, but they're also powerful. However, the functionality
is still limited to client server web requests. To intercept other method calls or to i ne‐tune the
interception, you need a much more sophisticated approach.
J2EE did not offer an out‐of‐the‐box AOP solution but worked in harmony with third‐party
frameworks. Java EE 5 introduced interceptors, which resulted in an easy‐to‐use built‐in aspect
approach. However, the interceptor concept was limited to Enterprise JavaBeans (EJB) until Context
and Dependency Injection (CDI) was introduced.
Interceptors in Java EE work in a similar way to aspects. Each interceptor addresses the concern
and hosts the code block that contains the functionality to be added. The target to be decorated is
called an advice . Each call to an advice within the scope of the interceptor is intercepted. The exact
location of the aspect to be executed is called the p ointcut .
Basic Java EE interceptors can only work on EJBs. Imagine an application consisting of hundreds
of EJBs. The whole application can be coni gured to log all EJB calls by deploying an interceptor
targeting all those EJBs.
Implementing interceptors in Java EE is straightforward. The i rst step is to create a new interceptor
class and annotate it with the @Interceptor annotation. This class hosts the advice code. Any
method annotated with @AroundInvoke is executed at the pointcut. However, there are some syntax
rules regarding the pointcut method signature:
Any pointcut method must return an object of type Object and have a parameter of type
InvocationContext .
Throw an exception.
You can use the InvocationContext parameter to access information about the current context as
seen in Listing 8‐4.
LISTING 8‐4: Simple implementation of an interceptor
package com.devchronicles.interceptor;
import javax.interceptor.AroundInvoke;
import javax.interceptor.InvocationContext;
public class SecurityInterceptor {
    public Object doSecurityCheck(InvocationContext context) throws Exception{
        //Do some security checks!
Search WWH ::

Custom Search