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:

@Override
@Transactional(rollbackFor = Exception.class)
public void executeTransaction() {
Optional<Customer> customerOptional = customerRepository.findById(1L);
Customer customer = customerOptional.get();
Payment payment1 = new Payment();
payment1.setState(102);
payment1.setDescription("payment from app");
payment1.setCustomer(customer);
paymentRepository.save(payment1);
TransactionSynchronizationManager.registerSynchronization(new TransactionSynchronizationAdapter() {
@Override
public void afterCommit() {
log.info("inside after submit");
Customer customer = new Customer();
customer.setFirstName("Lucy");
customer.setLastName("Lee");
customerService.store(customer);
}
});
}
// customerService.store
@Override
@Transactional(propagation = Propagation.REQUIRES_NEW)
public Customer store(Customer customer) {
Customer savedCustomer = customerRepository.save(customer);
}

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.