4

I'm facing a strange behaviour using AspectJ for a pointcut using my custom annotation.

The pointcut I use is:

@AfterThrowing(pointcut="@annotation(com.core.meta.NotifyOnFailure)", throwing="ex")

The problem I have is that my aspect is executed twice but if I modify the pointcut to:

@AfterThrowing(pointcut="execution(* sendAndReceive(..))", throwing="ex")

It runs once as expected.

The only method I have that raises the aspect is this:

    @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;
    }

Any idea about why my aspect is executed twice when using my custom annotation and only once when I use execution pointcut?

Federico Piazza
  • 30,085
  • 15
  • 87
  • 123

1 Answers1

10

Make sure you also restrict the pointcut to execution. Otherwise it will only be restricted to the annotation and thus be used for both call and execution (if AspectJ can advise the call of your method, which it can since it is in your own code). A good comparison between both is here: https://stackoverflow.com/a/18149106/2191746

Your pointcut would then look like this:

@AfterThrowing(pointcut="execution(* *(..)) && @annotation(com.core.meta.NotifyOnFailure)", throwing="ex")

No guarantee on the syntax, as I don't have an aspectJ compiler at hand.

Community
  • 1
  • 1
sheltem
  • 3,754
  • 1
  • 34
  • 39