The most common solution to these kinds of problems is to add a little bit of code
at the beginning and end of every method, implementing the logic to profile or
log in each method. This approach, however, has problems: the logic needs to
be implemented several times, and; if we later wish to modify or remove the
functionality, we need to modify several methods.
Aspect-oriented programming ( AOP ) is a programming paradigm that solves
the problems mentioned earlier by providing a way to implement the logic to be
executed just before and/or just after a method's main logic in a separate class.
EJB 3.0 introduced the ability to implement AOP via interceptors .
Implementing AOP via interceptors consists of two steps: coding the Interceptor
class and decorating the EJBs to be intercepted with the @Interceptors annotation.
These steps are described in detail in the next section.
Implementing the Interceptor class
An interceptor is a standard Java class. It must have a single method with the
public Object methodName(InvocationContext invocationContext) throws
Notice that the method must be decorated with the @AroundInvoke annotation,
which marks the method as an interceptor method. The InvocationContext
parameter can be used to obtain information from the intercepted method, such as its
name, parameters, the class that declares it, and more. InvocationContext also has
a proceed() method that is used to indicate when to execute the method logic.
The following table summarizes some of the most useful InvocationContext
methods. Refer to the Java EE 7 JavaDoc for the complete list (it is accessible
within NetBeans by going to Help | JavaDoc References | Java (TM) EE 7
Specification APIs ).
This returns an instance of the java.lang.reflect.
Method class, which can be used to introspect the
This returns an array of objects containing the parameters
passed to the intercepted method.
This returns the object containing the method being
invoked. Its return value is java.lang.Object .
This invokes the method being intercepted.