Mr. Nicky
Mr. Nicky

Reputation: 1669

Spring: How to commit transaction before entering @AfterReturning advice

I've got a transactional service class:

@Service
@Transactional(...)
public class MyService() {

    public void myFunc() { 
       // some code
    }

}

Also the following Aspect:

@Aspect
public class MyAspect() {

    @AfterReturning(value = "execution(...") // pointcut matching myFunc()'s signature
    public void doSomethingAfterMyFunc() { 
       // some code
    }

}

The problem I'm facing is that upon entering the @AfterReturning advice, the transaction created from the execution of myFunc() is not yet committed, so the advice shares the same transaction. From what I've read this behavior is to be expected, but for my purposes I need the opposite - is there a way to commit myFunc()'s transaction before entering the advice?

Thanks in advance!

Upvotes: 4

Views: 2898

Answers (1)

pleft
pleft

Reputation: 7905

This is happening because of the @Transactional Aspect, so you have 2 aspects in your code so you have to set the Order as explained https://docs.spring.io/spring/docs/3.0.x/spring-framework-reference/html/aop.html#aop-ataspectj-advice-ordering

In your code you could set the order of your own aspect MyAspect like the following:

@Aspect
@Order(1)
public class MyAspect() {
 //your code here
}

By specifying its order to 1 and since the rule is that:

On the way out from the joinpoint, the advice with highest Order value gets executed first.

the @Transactional Aspect will be executed prior yours so myFunc will get commited and then doSomethingAfterMyFunc will be executed.

Upvotes: 2

Related Questions