In a Spring application in a transactional method data shall be persisted and a file be written to the file system (with a path and a filename). Now, if the database transaction for some reason fails the file shall be deleted again from the file system.
To do that I was thinking of using an event listener as follows.
@TransactionalEventListener(phase = TransactionPhase.AFTER_ROLLBACK)
public void handleRollback() {
// remove file with the use of the path and file name
// (but where do those two parameters come from?)
}
However, inside that event listener I would need the properties value
of the path and fileName
to know which file to delete. but the event leading to a rollback I assume would be fired by Spring and I cannot pass values along with it.
So how could I process the rollback?
The standard solution seems to work as follows. The event containing all the data which is necessary in the rollback is always being published from the transactional method. The listener is only called in case of the rollback.
@Transactional
public void executeTransactionCode(final Long id) {
MyRollbackEvent myRollbackEvent = ... create the event with the necessary data ...
applicationEventPublisher.publishEvent(myRollbackEvent);
executeDBCode();
}
And the rollback event listener
@TransactionalEventListener(phase = TransactionPhase.AFTER_ROLLBACK)
public void handleRollback(final MyRollbackEvent event) {
// code to handle rollback, data now available through the event
}
Even if the listener fails with an exception the rollback is still being executed.