Spring AOP和异常拦截

8

我正在尝试配置Spring,以便在抛出特定异常子类(MyTestException)时执行通知:

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配置文件:

<bean name="interceptor" class="org.me.myproject.MyTestExceptionInterceptor"/>

<aop:config>
  <aop:advisor advice-ref="interceptor" pointcut="execution(???)"/>
</aop:config>

我有一种感觉,应该使用target切入点指示器(而不是execution),因为根据Spring文档的说法,似乎target允许我指定要匹配的异常类型,但我不确定是否正确,或者我的pointcut属性需要看起来像什么。
我非常希望在XML中完成AOP配置(而不是Java /注释),但如果需要,我可能可以将基于注释的解决方案转换为XML。
2个回答

9

我会使用<aop:after-throwing>元素和它的throwing属性。

Spring配置

<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和方法组合定义了方面适用的异常类型。在这个例子中,ThrowingClass抛出AnException和AnotherException。只有AnException将应用advice,因为advice的方法签名。 在Github上查看完整源代码的示例项目

1

看看 AfterThrowingAdvice。你可以在这里找到一个例子(搜索“After throwing advice”)。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接