Commit UnitOfWork vs Publish Events


In DefaultUnitOfWork.doCommit() (see code below from 2.3.2) it looks like events are published before the actual commit.

  1. What is the reason for publishing the events before the commit?

  2. Is there any way to publishing the events after the commit (to avoid publishing if commit fails)?

/ Guran P

protected void doCommit() {

do {
} while (!this.eventsToPublish.isEmpty());
if (isTransactional()) {


in the unit of work, the events are published “as part of the commit”. If the unit of work is attached to a transaction, that transaction is committed after the publication of the events. The reason is that the event bus can participate in that transaction. For example, you publish to AMQP, and only commit the transaction if that succeeded.

If you use the SimpleCommandBus, this means handlers are invoked in the same transaction, causing a rollback to really roll back everything, including what possible handlers have done. It’s not so much best practice, but resembles the more traditional approach more, making it easier to understand what’s happening.

So your solution may be to attach the publication mechanism to the transaction (or use the afterCommit listeners) to release published messages to their respective consumers.