Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Aspect using pointcut=@annotation for @AfterThrowing is running twice

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?

like image 728
Federico Piazza Avatar asked Oct 18 '25 18:10

Federico Piazza


1 Answers

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.

like image 174
sheltem Avatar answered Oct 20 '25 07:10

sheltem



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!