First, Interceptor method
The EJB3 can intercept and overwrite bean methods through interceptors. This is somewhat like the around in AOP. The around method of AOP can modify the return value, parameter value of the blocked method, and even cancel the execution of the blocked method. EJB3 interceptors can be used in stateless session beans, stateful session beans, and message-driven bean (MDB) methods. The easiest way to implement interceptors is to use the Interceptor method. That is, as long as you annotate a method with @aroundinvoke in the current bean (the class on the interceptor is in the Javax.interceptor package), the method becomes the interceptor method that blocks all the methods in the current bean. The implementation process is as follows:
@Stateful public
class Greeterbean implements Greeter
{
@AroundInvoke public
Object Myinterceptorm ETHOD1 (Invocationcontext ic) throws Exception
{
System.out.println ("myInterceptorMethod1:" + Ic.getmet Hod (). GetName ());
obj = Ic.proceed ();
}
@AroundInvoke public
Object myInterceptorMethod2 (Invocationcontext ic) throws Exception
{
S Ystem.out.println ("MYINTERCEPTORMETHOD2:" + Ic.getmethod (). GetName ());
obj = Ic.proceed ();
}
@Override public
String greet (string name)
{return
"hello" + name;
}
}
Two interceptor methods and one bean method are defined in the stateful session bean above. When the client invokes the greet method, the EJB container invokes the MyInterceptorMethod1 method first, then calls the MyInterceptorMethod2 method, and finally the greet method is invoked. There are several points to note when using the Interceptor method:
1. The Interceptor method must have a return value, and the return value type is object.
2. The Interceptor method can have only one parameter, and the parameter type must be Javax.interceptor.InvocationContext.
3. The EJB container will call the next interceptor method or the blocked Bean method only if the proceed method of the Invocationcontext interface is invoked.
4. Because the proceed method requires a exception exception to be thrown, the Interceptor method must throw a exception exception, or use Try...catch in the Interceptor method to catch the exception thrown by the proceed method.