In which order are annotations processed by Spring AOP?

114 views Asked by At

I have a method that has two annotations:

@Transactional
@SchedulerLock
public void test() {
    // do something
}

I'm wondering what happens first. Will first be a transaction created and then the locking will happen, or the other way round? Or isn't this even determined?

I tried to figure this out by reading the documentation, but I'm unsure where to even start. The only thing I could find was a random comment without source that said that the order is random.

1

There are 1 answers

0
Sergey Tsypanov On

In general the relative order of annotation aspect is not specified be default, moreover it might vary from version to version.

As it is mentioned in the answer to this question you can specify the order:

You need to change relative order of @Transactional and @Cacheable aspects.

The link there points to outdated documentation, so if you really need ordering I'd split this method into two, moving each into separate component and call one from another one (or vice versa), e.g.:

class A {
  private final B b;

  @SchedulerLock
  public void test() {
    b.test();
  }
}

class B {

  @Transactional
  public void test() {
    // do smth
  }
}