EJB 3 透過攔截器實現類 AOP Around 建議:修改返回值/參數、甚至取消目標方法執行。適用於無狀態/有狀態 Session Bean 與 MDB。本文詳解兩種實現方式與調用順序控制。
在 Bean 類中以 @AroundInvoke 註解標記方法,即成為攔截器方法,攔截當前 Bean 所有方法。簽名強制:
Objectjavax.interceptor.InvocationContextException 或捕獲 proceed() 異常ic.proceed() 才會繼續執行下一攔截器或目標方法@Stateful
public class GreeterBean implements Greeter {
@AroundInvoke
public Object myInterceptorMethod1(InvocationContext ic) throws Exception {
System.out.println("myInterceptorMethod1:" + ic.getMethod().getName());
return ic.proceed();
}
@AroundInvoke
public Object myInterceptorMethod2(InvocationContext ic) throws Exception {
System.out.println("myInterceptorMethod2:" + ic.getMethod().getName());
return ic.proceed();
}
@Override
public String greet(String name) { return "hello " + name; }
}
調用順序:myInterceptorMethod1 → myInterceptorMethod2 → greet。
@AroundInvoke。@Interceptors(MyInterceptor.class) 引用。@Interceptors({MyInterceptor.class, MyInterceptor1.class})。@Interceptors 陣列順序(先 MyInterceptor,後 MyInterceptor1)。在目標方法上標註 @ExcludeClassInterceptors,可阻止攔截器類的方法攔截該方法,但Bean 內部攔截器方法仍生效。
@ExcludeClassInterceptors
public String getValue() { return "abcd"; }