2011-12-01 8 views
7

インターセプト例外:春AOPと特定の例外サブクラス(<code>MyTestException</code>)がスローされたとき、私はそれがアドバイスを実行されるように春を設定しようとしている

public class MyTestExceptionInterceptor implements ThrowsAdvice { 
    public void afterThrowing(Method method, Object[] args, Object target, Exception exc) { 
     // I want this to get executed every time a MyTestException is thrown, 
     // regardless of the package/class/method that is throwing it. 
    } 
} 

とXML設定:

​​

によれば、ポイントカット指定子(executionではなく)を使用する必要があるという気持ちがあります。targetは、私がagainsと一致する例外の種類を指定できるようですそれが間違っているかどうか、または私のpointcut属性がどのように見える必要があるのか​​分かりません。

は私がを大幅には、Java /注釈とは対照的に、(XMLで行わAOPの設定を維持することを好むだろうが、必要であれば、私はおそらく、XMLへのアノテーションベースのソリューションを変換することができます。

答えて

8

私が使用したいです<aop:after-throwing> elementとそのthrowing属性。

春のコンフィグ

<bean name="tc" class="foo.bar.ThrowingClass"/> 

<bean name="logex" class="foo.bar.LogException"/> 

<aop:config> 
    <aop:aspect id="afterThrowingExample" ref="logex"> 
    <aop:after-throwing method="logIt" throwing="ex" 
         pointcut="execution(* foo.bar.*.foo(..))"/> 
    </aop:aspect> 
</aop:config> 

throwing属性は例外に呼び出される縦横のハンドラメソッド(ここでは、それはLogException.logItだ)のパラメータ名です:

アスペクト

public class LogException { 
    public void logIt(AnException ex) { 
     System.out.println("*** " + ex.getMessage()); 
    } 
} 

XMLおよび方法コンボは、アスペクトが適用される例外のタイプを定義しますに。この例では、ThrowingClassAnExceptionAnotherExceptionをスローします。アドバイスのメソッドシグネチャにより、AnExceptionにのみアドバイスが適用されます。

See example project on github for full source

1

AfterThrowingAdviceをチェックしてください。例はhere(「アドバイスを投げた後」を検索します)が見つかります。

関連する問題