代码
1. public Object invoke(MethodInvocation invocation) throws Throwable {
2. // Work out the target class: may be null.
3. // The TransactionAttributeSource should be passed the target class
4. // as well as the method, which may be from an interface
5. Class targetClass = (invocation.getThis() != null) ? invocation.getThis().getClass() : null;
6.
7. // Create transaction if necessary.
8. TransactionInfo txInfo = createTransactionIfNecessary(invocation.getMethod(), targetClass);
9.
10. Object retVal = null;
11. try {
12. // This is an around advice.
13. // Invoke the next interceptor in the chain.
14. // This will normally result in a target object being invoked.
15. retVal = invocation.proceed();
16. }
17. catch (Throwable ex) {
18. // target invocation exception
19. doCloseTransactionAfterThrowing(txInfo, ex);
20. throw ex;
21. }
22. finally {
23. doFinally(txInfo);//业务方法出栈后必须先执行的一个方法
24. }
25. doCommitTransactionAfterReturning(txInfo);
26. return retVal;
27. }
代码
1. protected TransactionInfo createTransactionIfNecessary(Method method, Class targetClass) {
2. // We always bind the TransactionInfo to the thread, even if we didn't create
3. // a new transaction here. This guarantees that the TransactionInfo stack
4. // will be managed correctly even if no transaction was created by this aspect.
5. txInfo.bindToThread();
6. return txInfo;
7. }
就是这个bindToThread()方法在作怪:
1. private void bindToThread() {
2. // Expose current TransactionStatus, preserving any existing transactionStatus for
3. // restoration after this transaction is complete.
4. oldTransactionInfo = (TransactionInfo) currentTransactionInfo.get();
5. currentTransactionInfo.set(this);
6. }