1.12.11

Java EE Interceptors

Interceptors are the pragmatic implementation of Aspect Oriented Programming within the Java EE stack. At the current version JEE 6 there exist two different technologies providing this functionality Enterprise Java Beans and Context Dependency Injection (if you have the choice, use the CDI implementation as it offers far more functionalities)

Why we want it
Interceptors are mostly used for so called cross cutting concerns (c-c) like logging, security or infrastructural code. Such concerns are, briefly speaking, occuring at very many different places in many different classes. And as programmers who care about code readability, we do not want to pollute our beautiful business logic with such stuff. Thanks to Intercepors, we can put that code for the c-c concern in some other far far away class. After that we just need to annotate classes or methods that we want to intercept. Thereby it is possible to execute our c-c code before or after the actual business logic method.

How the magic happens
Adam Bien wrote a short and simple blog entry about how to implement an EJB Interceptor, really good one. CDI interceptors can be found here.
First, the Interceptor needs to be implemented, how depends on the technology (EJB, CDI). Second, annotate the class (all methods) or specific method you want to activate the Interceptor for. Thats it. After deployment, the container always automatically runs the Interceptor before the business logic method is executed. It is as simple as that.

Criticism
It might happen that people who are not really into Java EE mechanisms will come up with following arguments against Interceptors:
  • Black Magic - As they do not really know how Interceptors work and what their benefits are, they will simple declerate them as evil.
  • Difficult to Test - Not true at all ... The logic within the Interceptor class can be Unit-tested as in any other class; simply mock the InvocationContext if necessary. Furthermore, if you want to test the actual business logic, instantiate the class and  simply invoke the Interceptor's method manually. Last but not least, the integration test of all components has to be done anyway, with or without Interceptors.
  • Difficult to trace back- It may be kind of true that if some programmer is debugging your code not knowing about the Interceptor, might have some troubles, especially if the Interceptor is just defined in XML. So a general advice would be to always annotate your intercepted classes and to avoid XML configuration. Furthermore, if you are debugging someone else's EJBs, always look out for Interceptor annotations :)
If you know more arguments against Interceptors, or have something else to add, please feel free :)

No comments:

Post a Comment