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

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

CHAPTER 8 ■ CALLBACKS AND INTERCEPTORSFigure 8-4. A call to a business method being interceptedMethod InterceptorsListing 8-3 defines an interceptor that is only available for CustomerEJB. But most of the time you want toisolate a cross-cutting concern into a separate class and tell the container to intercept the calls onseveral session beans. Logging is a typical example of a situation when you want all the methods of allyour EJBs to log entering and exiting messages. To specify an interceptor, you need to develop a separateclass and instruct the container to apply it on a specific bean or bean’s method.To share some code among multiple beans, let’s take the logMethod() from Listing 8-3 and isolate itin a separate class as shown in Listing 8-4. As you can see, LoggingInterceptor is a simple POJO that hasa method annotated <strong>with</strong> @AroundInvoke.Listing 8-4. An Interceptor Class Logging a Method on Entering and Exitingpublic class LoggingInterceptor {private Logger logger = Logger.getLogger("com.apress.javaee6");@AroundInvokepublic Object logMethod(InvocationContext ic) throws Exception {logger.entering(ic.getTarget().toString(), ic.getMethod().getName());try {return ic.proceed();} finally {logger.exiting(ic.getTarget().toString(), ic.getMethod().getName());}}}247

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

Saved successfully!

Ooh no, something went wrong!