Add Callback for Spring Transaction

TransactionSynchronization is an interface that enable us to add callbacks for transaction synchronization, such as send message after a successful commit. You can view official information here.

I will show the way to use TransactionSynchronization in the following example:

By operation defined in afterCommit, after the transaction successfully commit the payment to database, it will start a new transaction to commit the customer, as customerService.store annotation-propagation = Propagation.REQUIRES_NEW require. (@Transactional(propagation = Propagation.REQUIRES_NEW) is required for the operation in "afterCommit", otherwise the operation is bound to the existing transaction, not the new one, and this cause the new commit takes no effect).

TransactionSynchronization have other operation choices, such as afterCompletion(int status), beforeCommit.