2012-02-23 26 views
0

我需要在無狀態bean方法的每次調用之前執行邏輯。在每個無狀態bean方法之前執行一些邏輯

例子:

class MyStatelessBean 
{ 
    void myPreExecutionLogic() 
    { 
     System.out.println("pre method execution logic"); 
    } 

    void method1() 
    { 
     System.out.println("method 1"); 
    } 

    void method2() 
    { 
     System.out.println("method 2"); 
    } 
} 

有這樣使用EJB的一種方式?註冊某種監聽器或註釋myPreExecutionLogic(如@PreConstruct)?

回答

1

如果你正在使用EJB3,您可以使用Interceptors@AroundInvoke

建立一個攔截器類與@AroundInvoke註釋

public class MyInterceptor { 

    @AroundInvoke 
    public Object doSomethingBefore(InvocationContext inv) { 
     // Do your stuff here. 
     return inv.proceed(); 
    } 
} 

然後註釋與類名

public class MyStatelessBean { 

     @Interceptors ({MyInterceptor.class}) 
     public void myMethod1() { 
你的EJB方法
+0

這是正確的答案。我有一個錯誤。 +1 – 2012-02-23 16:37:57

+0

哼,好的。我閱讀了你提到的[article](http://weblogs.java.net/blog/meeraj/archive/2006/01/interceptors_wi.html),並得出結論,下面的例子將解決我的部分問題。 「類MyStatelessBean { @AroundInvoke 空隙myPreExecutionLogic(InvocationContext invocationContext)
{ 的System.out.println( 「預方法執行邏輯」);
} void method1() { System.out.println(「method 1」); } }' 在抽象超類中有這樣做的方法嗎? 我需要所有的子類方法被攔截。 – 2012-02-23 16:56:45

+0

@Wagner - 是的。你可以在超類本身上定義你的攔截器。然後所有的子類方法都會被攔截。 – Kal 2012-02-23 19:36:40

0

Kal的答案有點變化,我設法使該方法與示例中聲明的類相同(讓我想起junits @Before)。

也不要忘記「拋出異常」從實際的方法調用拋出異常的方法簽名的內部ctx.proceed()

class MyStatelessBean 
{ 

    @AroundInvoke 
    public Object myPreExecutionLogic(InvocationContext ctx) throws Exception{ 
     System.out.println("pre method execution logic"); 

     return ctx.proceed(); 
    } 

    void method1() 
    { 
     System.out.println("method 1"); 
    } 

    void method2() 
    { 
     System.out.println("method 2"); 
    } 
} 
相關問題