Declarative transaction management simplifies considerably the development. Sometimes you want a little more control over transaction but at the same time you don't want to switch to programmatic transaction management. I'm talking about cases when you want to execute some activities only when transaction was completed successfully. For example: send an email with registration details, update a cache, send a message over network, etc. The tricky part here is that you want to perform these activities from a transactional method (a method marked with @Transactional which automatically will start and end the transaction).
Now let's see how we can achieve this in Spring Framework. TransactionSynchronizationManager is the central helper class that manages resources and transaction synchronizations per thread. It allows to register transaction synchronizations for the current thread if synchronization is active. TransactionSynchronization represents the actual transaction synchronization callback with methods like: afterCommit(), afterCompletion(int status), beforeCommit(boolean readOnly), beforeCompletion(), etc. In order to make things easier for use, we will create an after commit executor which will allow us to execute the code only after a successful commit.
Read More »