2011-10-03 25 views
1

我很努力写/配置,我想拦截我的整个项目抛出的所有异常一个ThrowsAdvice拦截:Spring AOP的配置为拦截所有异常

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完美的作品,并精确拦截时被调用我的主:: DoSomething的()方法 - 所以我知道我磁道上。使用XMLSPY来看看Spring AOP的架构,它看起来像我可以添加类似以下面让我ExceptionsInterceptor拦截所有抛出的异常:

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

但是我找不到在哪里,这是用作任何文件例如,我不知道如何配置方法属性,使其“通配符”(*)并匹配所有类和所有方法。

任何人都可以指向正确的方向吗?提前致谢!

回答

2

根据AspectJ的示例方法的参数是指@AfterThrowing建议方法:

@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" /> 

希望它能帮助。

+0

谢谢,我很欣赏的响应。你可能已经有95%的成功率。只是好奇,但:在AfterThrowing注释,切入点属性的执行符似乎表明,你只能有1个方法的拦截例外。我期待有*每个*类的每个*方法被拦截,当抛出异常时。你能否详细说明或者指向一些优秀文学的方向?再次感谢! – IAmYourFaja

+0

坦率地说,我想对你唯一的选择,你是使用@Pointcut(“内(org.me.myproject。*)”),这将在包org.me.myproject或其子包的每一个方法适用的建议。我认为没有其他办法可以做到。 –