Java Reference
In-Depth Information
The
@Interceptors
annotation can be used at the method level, in which case it
applies only to the method it decorates, or at the class level, in which it applies to
every method in the bean.
The following example is a new version of our
EchoBean
session bean, slightly
modified to have its
echo()
method intercepted by the
LoggingInterceptor
,
that we wrote in the previous section.
package com.ensode.sessionbeanintro.ejb;
import javax.ejb.Stateless;
import javax.ejb.TransactionAttribute;
import javax.ejb.TransactionAttributeType;
import javax.interceptor.Interceptors;
@Stateless
public class Echo implements EchoRemote {
// Add business logic below. (Right-click in editor and choose
// "Insert Code > Add Business Method")
@Interceptors({LoggingInterceptor.class})
@TransactionAttribute(TransactionAttributeType.REQUIRES_NEW)
public String echo(String saying) {
return "echoing: " + saying;
}
}
Notice that the only change we had to make to our session bean was to add the
@
Interceptors
annotation to its
echo()
method. In this particular case, the class
array attribute has a single value, which is the
LoggingInterceptor
class we
defined above. This has the effect of executing all the code in the interceptor's
logMethodCall()
method before the
invocationContext.proceed()
call just
before the method is executed, and all the code after the
invocationContext.
proceed()
call just after the method ends. In our example, we are using a single
interceptor for our bean's method. If we need our method to be intercepted by
more than one interceptor, we can do that by adding additional interceptor classes
between the curly braces in the
@Interceptors
annotation, the list of interceptors
between the curly braces must be separated by commas.
At this point we are ready to test our interceptor. In NetBeans, we can simply
right-click on the project in the
Projects
window and select
Run
. After doing so,
we should see the output of the interceptor's
logMethodCall()
in NetBean's
GlassFish output window.