Description
Oliver Drotbohm opened SPR-12080 and commented
Spring provides an ApplicationEventPublisher
API that can be used to publish events to other application components. By default, the events are published synchronously using a SimpleApplicationEventMulticaster
when invoking ApplicationEventPublisher.publishEvent(…)
directly.
In user applications the events publish very often signal the outcome of a business action (e.g. "user created"). Thus it's crucial that these events are only published if the transaction succeeds and thus also after the transactions has concluded.
In this repository I built a proof of concept implementation of an ApplicationEventMulticaster
that registers a TransactionSynchronization
for ApplicationEvents
of a certain type (TransactionBoundApplicationEvent
in my case). This way, the immediate multicasting is delayed to after the transaction commit.
This basically works and can be seen in action in the Spring RESTBucks example (necessary configuration, the transaction-bound event and event throwing code). There are a few things that could be changed, added on top or improved:
- Instead of the type-based detection of transaction-bound events could be augmented by inspecting the event object for a dedicated annotation.
- Currently the special
TransactionAwareApplicationEventMulticaster
has to be configured manually currently. However, it could probably registered automatically if the Spring transaction module is on the classpath. (I can also imagine Boot doing that kind of auto-configuration for now).
Issue Links:
- CDI-like transaction-aware events for [SPR-10633] #15261 CDI-like transaction-aware events for ("is duplicated by")
- ApplicationListener-like annotation for consuming application events [SPR-11622] #16245 ApplicationListener-like annotation for consuming application events
Referenced from: commits 4741a12
0 votes, 13 watchers