12.07.2015 Views

Beginning Java EE 6 with GlassFish 3, Second Edition

Beginning Java EE 6 with GlassFish 3, Second Edition

Beginning Java EE 6 with GlassFish 3, Second Edition

SHOW MORE
SHOW LESS

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

CHAPTER 8 ■ CALLBACKS AND INTERCEPTORSLife-Cycle InterceptorIn the first part of this chapter, you learned how to handle callback events in your EJB. With a callbackannotation, you can inform the container to invoke a method at a certain life-cycle phase(@PostConstruct, @PrePassivate, @PostActivate, and @PreDestroy). For example, if you want to log anentry each time a bean instance is created, you just need to add a @PostConstruct annotation on onemethod of your bean and add some logging mechanisms to it. But what if you need to capture life-cycleevents across many types of beans? Life-cycle interceptors allow you to isolate some code into a classand invoke it when a life-cycle event is triggered.Life-cycle interceptors really look like what you’ve just seen in Listing 8-4. Instead of @AroundInvoke,methods can be annotated <strong>with</strong> callback annotations. Listing 8-6 shows the ProfileInterceptor class<strong>with</strong> two methods: logMethod(), used for postconstruction, and profile(), used for predestruction.Listing 8-6. A Life-Cycle Interceptor Defining Two Methodspublic class ProfileInterceptor {private Logger logger = Logger.getLogger("com.apress.javaee6");@PostConstructpublic void logMethod(InvocationContext ic) {logger.entering(ic.getTarget().toString(), ic.getMethod().getName());try {return ic.proceed();} finally {logger.exiting(ic.getTarget().toString(), ic.getMethod().getName());}}@PreDestroypublic void profile(InvocationContext ic) {long initTime = System.currentTimeMillis();try {return ic.proceed();} finally {long diffTime = System.currentTimeMillis() - initTime;logger.fine(ic.getMethod() + " took " + diffTime + " millis");}}}As you can see in Listing 8-6, life-cycle interceptor methods take an InvocationContext parameter,return void instead of Object (because life-cycle callback methods return void, as explained earlier in the“Callbacks” section), and cannot throw checked exceptions.To apply the interceptor defined in Listing 8-6, the session bean needs to use the @Interceptorsannotation. As you can see in Listing 8-7, CustomerEJB defines the ProfileInterceptor. When the EJB isinstantiated by the container, the logMethod() of the interceptor will be invoked prior to the init()method. Then, if a client calls createCustomer() or findCustomerById(), no interception will happen.But, before CustomerEJB is destroyed by the container, the profile() method will be invoked.249

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!