Spring AOP和异常拦截

IAm*_*aja 7 spring spring-aop

我正在尝试配置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.
    }
}
Run Code Online (Sandbox Code Playgroud)

和XML配置:

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

<aop:config>
  <aop:advisor advice-ref="interceptor" pointcut="execution(???)"/>
</aop:config>
Run Code Online (Sandbox Code Playgroud)

我有一种感觉,我应该使用target切入点说明符(而不是execution),因为 - 根据Spring文档 - 似乎target允许我指定匹配的异常类型,但我不确定这是否错误,或者我的pointcut属性需要看起来像什么.

我将大大宁愿保持在XML完成(而不是到Java /注解的AOP配置,但如果需要的话我大概可以翻译基于注解式的解决方案为XML.

Dav*_*ton 8

我会使用一个<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>
Run Code Online (Sandbox Code Playgroud)

throwing属性是LogException.logIt在异常上调用的方面的处理程序方法(此处为)的参数名称:

方面

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

XML和方法组合定义了方面适用的异常类型.在这个例子中,ThrowingClass抛出AnExceptionAnotherException.AnException由于建议的方法签名,只会应用建议.

有关完整源代码,请参阅github上的示例项目.