2012-02-23 11 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を使ってこれを行う方法はありますか?何らかのリスナーを登録するか、@PreConstructのようなmyPreExecutionLogicに注釈を付けますか?

答えて

1

あなたはEJB3を使用している場合は、@AroundInvokeアノテーションを

public class MyInterceptor { 

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

でインターセプタクラスを設定Interceptors@AroundInvoke

を使用することができます。そして、クラス名

public class MyStatelessBean { 

     @Interceptors ({MyInterceptor.class}) 
     public void myMethod1() { 
を使用してEJBメソッドに注釈を付けます
+0

内の実際のメソッド呼び出しからスローされた例外のためのメソッドシグネチャの「例外をスロー」忘れないでください。鉱山に誤りがありました。 +1 –

+0

ハム、ok。あなたが言及した以下の例が私の問題の一部を解決すると結論づけた[記事](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"); } } ' 抽象スーパークラスでこれを行う方法がありますか? 私は、すべてのサブクラスメソッドを傍受する必要があります。 –

+0

@Wagner - はい。スーパークラス自体にインターセプタを定義することができます。その後、すべてのサブクラスメソッドがインターセプトされます。 – Kal

0

Kalの答えが少し変わったので、私は宣言されている例と同じクラスでメソッドを作りました(私に思い出させるジュニット@前)

も正しい答えだ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"); 
    } 
} 
関連する問題