Java Reference
In-Depth Information
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.
EJB Timer Service
Stateless session beans and message-driven beans (another type of EJB discussed
in the next chapter) can have a method that is executed automatically at regular
intervals. This functionality is useful in case we want to execute some logic
periodically (once a week, every day, every hour, etc.) without having to explicitly
call any methods. This functionality is achieved by the
EJB timer service
.
In order to use the EJB timer service, an instance of
javax.ejb.TimerService
must be injected into the EJB via the
@Resource
annotation. This object will be used
to create and cancel timers in two different methods in the EJB. Finally, the EJB
must have a method to be invoked when the timer expires. This method must be
decorated with the
@Timeout
annotation. The following example illustrates how to
use the EJB timer service.