首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> Java 程式設計 >> J2EE

EJB 3 攔截器完全指南:@AroundInvoke 方法攔截與 @Interceptors 類攔截實戰

     編輯:J2EE

EJB 3 透過攔截器實現類 AOP Around 建議:修改返回值/參數、甚至取消目標方法執行。適用於無狀態/有狀態 Session Bean 與 MDB。本文詳解兩種實現方式與調用順序控制。

一、攔截器方法:最簡單,定義在 Bean 內部

在 Bean 類中以 @AroundInvoke 註解標記方法,即成為攔截器方法,攔截當前 Bean 所有方法。簽名強制:

  • 返回 Object
  • 單一參數 javax.interceptor.InvocationContext
  • 必須拋出 Exception 或捕獲 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。

二、攔截器類:跨 Bean 重用,配合 @Interceptors

  1. 創建獨立類,方法同樣標註 @AroundInvoke。
  2. 在目標 Bean 上用 @Interceptors(MyInterceptor.class) 引用。
  3. 多個攔截器類:@Interceptors({MyInterceptor.class, MyInterceptor1.class})。

三、調用順序鐵律

  1. 優先調用攔截器類中的方法,按 @Interceptors 陣列順序(先 MyInterceptor,後 MyInterceptor1)。
  2. 再調用Bean 內部的攔截器方法(按定義順序)。

四、排除攔截:@ExcludeClassInterceptors

在目標方法上標註 @ExcludeClassInterceptors,可阻止攔截器類的方法攔截該方法,但Bean 內部攔截器方法仍生效。

@ExcludeClassInterceptors
public String getValue() { return "abcd"; }
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved