2011-12-01 128 views
7

我想配置Spring以便它执行的建议时,一个特定的异常子类(MyTestException)被抛出:Spring AOP和异常拦截

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

​​

我有一种感觉,我应该使用target切入点说明符(而不是execution),因为 - 根据Spring docs - 看起来好像target允许我指定异常的类型以再次匹配吨,但我不确定这是错误的,还是我的属性需要看起来像。

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

回答

8

我会使用一个<aop:after-throwing> element及其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将引发AnExceptionAnotherException。由于建议的方法签名,只有AnException将应用建议。

See example project on github for full source

1

查看AfterThrowingAdvice。找到一个例子here(搜索“投掷建议后”),你会发现它。