问题
I have a requirement to do a task after execution of a function. I have used Aspect for this. but I have some confusion.
I have a function A() in a spring service.
@Transactional(readOnly = false,
isolation = Isolation.DEFAULT,
propagation = Propagation.REQUIRED,
rollbackFor = {Exception.class})
void A() {
//Do Something
}
I have an @Afterreturning
aspect on this function.
@AfterReturning(pointcut = "execution(Sevice.saverecord(..)) ")
public void processNotifications(JoinPoint jp) {}
I want to know whether this aspect will use the transaction of metod A() or it will create a new transaction automatically. As I have not defined any transaction on this aspect method.
I tried to print the transaction detail using TransactionAspectSupport.currentTransactionStatus().toString() in both method.I got two different IDs.
Can anybody explain Does it mean there are two transactions, If yes where this second transaction came from?
回答1:
Yes the @AfterReturning
aspect executes in the same transaction as that of the advised method.
The execution sequence while invoking a transactional method is depicted in below diagram (ref - spring docs)
The aspect (i.e. custom advisor) can be configured to run before or after the transaction advice, which by default is after.
For further reference on how to configure the custom advisor to run before the transaction advice make use of the Ordered as described here.
来源:https://stackoverflow.com/questions/39406242/afterreturning-aspect-executes-in-same-transaction-of-pointcut-method