使用pointcut = @ annotation for @AfterThrowing的Aspect正在运行两次

Fed*_*zza 2 java spring aspectj

我正在使用AspectJ使用我的自定义注释进行切入点的奇怪行为.

我使用的切入点是:

@AfterThrowing(pointcut="@annotation(com.core.meta.NotifyOnFailure)", throwing="ex")
Run Code Online (Sandbox Code Playgroud)

我遇到的问题是我的方面执行了两次,但如果我将切入点修改为:

@AfterThrowing(pointcut="execution(* sendAndReceive(..))", throwing="ex")
Run Code Online (Sandbox Code Playgroud)

它按预期运行一次.

我提出方面的唯一方法是:

    @NotifyOnFailure // I want to use this annotation to raise the aspect once
    public  String sendAndReceive(String serviceUrl)
    {
         String responseXml = "...";
         try
         {
             throw new Exception("test...");
         }
         catch(Exception x)
         {
            ExternalExecutionException ex = new ExternalApiExecutionException("Service failed");
            throw ex; 
         }
         finally
         {
             ...
         }          

        return responseXml;
    }
Run Code Online (Sandbox Code Playgroud)

任何关于为什么我的方面在使用我的自定义注释时执行两次而在使用execution切入点时只执行一次的想法?

she*_*tem 8

确保您还将切入点限制为执行.否则它将仅限于注释,因此可用于调用执行(如果AspectJ可以建议调用您的方法,它可以,因为它在您自己的代码中).两者之间的良好比较是:https://stackoverflow.com/a/18149106/2191746

你的切入点看起来像这样:

@AfterThrowing(pointcut="execution(* *(..)) && @annotation(com.core.meta.NotifyOnFailure)", throwing="ex")
Run Code Online (Sandbox Code Playgroud)

不保证语法,因为我手头没有aspectJ编译器.