【问题标题】:Spring AOP Configuration for Intercepting All Exceptions拦截所有异常的Spring AOP配置
【发布时间】:2011-10-03 16:01:58
【问题描述】:

我正在努力编写/配置一个 ThrowsAdvice 拦截器,我想拦截整个项目中抛出的所有异常:

public class ExceptionsInterceptor implements ThrowsAdvice
{
    public void afterThrowing(final Method p_oMethod, final Object[] p_oArgArray,
        final Object p_oTarget, final Exception p_oException)
    {
        System.out.println("Exception caught by Spring AOP!");
    }
}

我已经成功配置了一个 MethodInterceptor 实现,它拦截我想要分析的特定方法(查看它们执行需要多长时间)。这是我目前拥有的 XML 配置文件:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:aop="http://www.springframework.org/schema/aop"
xsi:schemaLocation="
    http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
    http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd"/>

<bean name="profilingInterceptor" class="org.me.myproject.aop.ProfilingInterceptor"/>

<bean name="exceptionsInterceptor" class="org.me.myproject.aop.ExceptionsInterceptor"/>

<aop:config>
    <aop:advisor advice-ref="profilingInterceptor" pointcut="execution(* org.me.myproject.core.Main.doSomething(..))"/>
</aop:config>

我的 ProfilingInterceptor 工作完美,并在我的 Main::doSomething() 方法被调用时准确地拦截 - 所以我知道我已经走上正轨了。使用 XmlSpy 来查看 Spring AOP 的架构,看起来我可以添加如下内容,以便让我的 ExceptionsInterceptor 拦截所有抛出的异常:

<aop:aspect>
    <after-throwing method=""/>
</aop:aspect>

但是我找不到任何将其用作示例的文档,并且我不知道如何配置方法属性,使其成为“通配符”(*) 并匹配所有类和所有方法。

谁能指出我正确的方向?提前致谢!

【问题讨论】:

    标签: java xml spring aop


    【解决方案1】:

    根据aspectJ示例方法参数参考@AfterThrowingadvice方法:

    @Aspect
    public class LoggingAspect {
    
      @AfterThrowing(
       pointcut = "execution(* package.addCustomerThrowException(..))",
       throwing= "error")
      public void logAfterThrowing(JoinPoint joinPoint, Throwable error) {
        //...
      }
    }    
    

    然后是配置:

     <aop:after-throwing method="logAfterThrowing" throwing="error"   />
    

    希望对你有帮助。

    【讨论】:

    • 谢谢,感谢您的回复。你可能已经让我走了 95% 的路。只是好奇:在 AfterThrowing 注释中,切入点属性的执行说明符似乎表明您只能拦截 1 个方法的异常。我希望在抛出异常时拦截 every 类的 every 方法。你能详细说明或指出一些好的文学的方向吗?再次感谢!
    • 坦率地说,我认为你唯一的选择是使用 @Pointcut("within(org.me.myproject..*)") 这将对包 org.me 的每个方法应用建议.myproject 或其子包。我认为没有其他方法可以做到这一点。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-07-24
    • 1970-01-01
    • 1970-01-01
    • 2018-01-31
    • 2014-02-03
    • 2023-03-17
    • 1970-01-01
    相关资源
    最近更新 更多