@Transactional public User createUser(User user){ User newUser = userRepository.save(user); emailService.sendEmail(user.getEmail()); return newUser; } }
@Transactional public Customer createCustomer(User user){ User newUser = userRepository.save(user); final UserCreatedEvent event = new UserCreatedEvent(newUser); applicationEventPublisher.publishEvent(event); return newUser; } }
// Throw UnexpectedRollbackException if we have a global rollback-only // marker but still didn't get a corresponding exception from commit. if (unexpectedRollback) { thrownew UnexpectedRollbackException( "Transaction silently rolled back because it has been marked as rollback-only"); } } catch (UnexpectedRollbackException ex) { // can only be caused by doCommit triggerAfterCompletion(status, TransactionSynchronization.STATUS_ROLLED_BACK); throw ex; } catch (TransactionException ex) { // can only be caused by doCommit if (isRollbackOnCommitFailure()) { doRollbackOnCommitException(status, ex); } else { triggerAfterCompletion(status, TransactionSynchronization.STATUS_UNKNOWN); } throw ex; } catch (RuntimeException | Error ex) { if (!beforeCompletionInvoked) { triggerBeforeCompletion(status); } doRollbackOnCommitException(status, ex); throw ex; }
// Trigger afterCommit callbacks, with an exception thrown there // propagated to callers but the transaction still considered as committed. try { triggerAfterCommit(status); } finally { triggerAfterCompletion(status, TransactionSynchronization.STATUS_COMMITTED); }
} finally { cleanupAfterCompletion(status); } }
接着看triggerAfterCommit的实现
1 2 3 4 5 6 7 8 9 10 11 12
/** * Trigger {@code afterCommit} callbacks. * @param status object representing the transaction */ privatevoidtriggerAfterCommit(DefaultTransactionStatus status){ if (status.isNewSynchronization()) { if (status.isDebug()) { logger.trace("Triggering afterCommit synchronization"); } TransactionSynchronizationUtils.triggerAfterCommit(); } }