Java Reference
In-Depth Information
cycle callback listeners. When the target bean transitions lifecycles, the annotated methods
in the interceptor class are triggered.
The following interceptor class logs when ActionBazaar beans allocate and release re-
sources when beans instances are constructed and destroyed:
public class ActionBazaarResourceLogger {
@PostConstruct
public void initialize(InvocationContext context) {
System.out.println("Allocating resources for bean: "
+ context.getTarget());
context.proceed();
}
@PreDestroy
public void cleanup(InvocationContext context) {
System.out.println("Releasing resources for bean: "
+ context.getTarget());
context.proceed();
}
}
As the code sample shows, lifecycle interceptor methods can't throw checked exceptions
(it doesn't make sense because there's no client for lifecycle callbacks to bubble a problem
up to).
Note that a bean can have the same lifecycle callbacks both in the bean itself as well as
in one or more interceptors. That's the whole point of calling the InvocationCon-
text.proceed() method in lifecycle interceptor methods as in the resource logger
code. This ensures that the next lifecycle interceptor method in the invocation chain or the
bean lifecycle method is triggered. There's absolutely no difference between applying an
interceptor class with or without lifecycle callbacks. The resource logger, for example, is
applied as follows:
@Interceptors({ActionBazaarResourceLogger.class})
public class PlaceBidBean { ... }
You might find that you'll use lifecycle callbacks as bean methods to manage resources a
lot more often than you use interceptor lifecycle callbacks to encapsulate crosscutting con-
cerns such as logging, auditing, and profiling. But interceptor callbacks are extremely use-
ful when you need them.
Search WWH ::




Custom Search