September 2010
Intermediate to advanced
766 pages
18h 35m
English
While it’s really nice that EJB provides aspectized handling of many of the container services, the specification cannot possibly identify all cross-cutting concerns facing your project. For this reason, EJB makes it possible to define custom interceptors upon business methods and lifecycle callbacks. This makes it easy to contain some common code in a centralized location and have it applied to the invocation chain without impacting your core logic.
Say we want to measure the execution time of all invocations to a particular method. We’d write an interceptor:
prototype MetricsInterceptor
{
function intercept(Invocation invocation)
{
// Get the start time
Time startTime = getTime();
// Carry out the invocation
invocation.continue();
// Get the end time
Time endTime = getTime();
// Log out the elapsed time
log("Took " + (endTime − startTime));
}
}Then we could apply this to methods as we’d like:
@ApplyInterceptor(MetricsInterceptor.class)
function myLoginMethod{ ... }
@ApplyInterceptor(MetricsInterceptor.class)
function myLogoutMethod{ ... }Interceptors are explained in Chapter 18.