What are Interceptors in Java EE?
Solution 1:
Interceptors are used to implement cross-cutting concerns, such as logging, auditing, and security, from the business logic.
In Java EE 5, Interceptors were allowed only on EJBs. In Java EE 6, Interceptors became a new specification of its own, abstracted at a higher level so that it can be more generically applied to a broader set of specifications in the platform.
They intercept invocations and life-cycle events on an associated target class. Basically, an interceptor is a class whose methods are invoked when business methods on a target class are invoked, life-cycle events such as methods that create/destroy the bean occur, or an EJB timeout method occurs. The CDI specification defines a type-safe mechanism for associating interceptors to beans using interceptor bindings.
Look for a working code sample at:
https://github.com/arun-gupta/javaee7-samples/tree/master/cdi/interceptors
Java EE 7 also introduced a new @Transactional annotation in Java Transaction API. This allows you to have container-managed transactions outside an EJB. This annotation is defined as an interceptor binding and implemented by the Java EE runtime. A working sample of @Transactional is at:
https://github.com/arun-gupta/javaee7-samples/tree/master/jta/transaction-scope
Solution 2:
Interceptors are used to add AOP capability to managed beans.
We can attach Interceptor to our class using @Interceptor annotation. Whenever a method in our class is called, the attached Interceptor will intercept that method invocation and execute its interceptor method.
This can be achieved using @AroundInvoke annotation ( see example below ).
We can intercept life cycle events of a class ( object creation,destroy etc) using @AroundConstruct annotation.
Main difference between Interceptor and Servlet Filters is We can use Interceptor outside WebContext, but Filters are specific to Web applications.
Common uses of interceptors are logging, auditing, and profiling.
For more detailed introduction, you can read this article. https://abhirockzz.wordpress.com/2015/01/03/java-ee-interceptors/