Search code examples
javaannotationsaopaspectjspring-annotations

AspectJ Expression for an existing annotation, pointcut after annotation but before method execution


Here's the existing code:

@Transactional
//  <-- Want to Pointcut to here, after Transactional is done, before method execution
public String getUsername(int userId) {
     ...
}

Trying to pointcut to the commented line, here's what I tried so far:

@Around("@annotation(org.springframework.transaction.annotation.Transactional) " +
        " && !target(org.springframework.transaction.interceptor.TransactionAspectSupport)")
public Object runQueryWithinTransaction(ProceedingJoinPointjp) throws Throwable {
     ...
}

Also tried setting the order of my aspect to LowestPrecedence. Despite all of this, I still see my Aspect being called before Transactional's "invokeWithinTransaction" method. Tried "@After" but that was executed after my "getUsername" method. Tried "@Before", for no reason, but that obviously didn't help.

What should I be doing instead?


Solution

  • Solved this by setting precedence in my aspect like so:

    @Aspect
    @DeclarePrecedence("org.springframework.transaction.aspectj.AnnotationTransactionAspect, *")
    public class MyAspect {
        ....
    }
    

    Thanks to @kriegaex, in case you aren't using AspectJ and regular Spring AOP, you should be trying to use @Ordered and @Order annotations. @Order on Spring Transactional annotation can be set in @EnableTransactionManagement annotation, and set a lower precedence (or none at all, since lowest precedence is default) for your own Aspect.