你可以使用TransactionSynchronizationManager而不需要破解PlatformTransactionManager。
注意:TransactionAware是一個標記接口,指示ApplicationListener想要在成功提交事務後接收事件。
public class TransactionAwareApplicationEventMulticaster extends SimpleApplicationEventMulticaster {
@Override
public void multicastEvent(ApplicationEvent event) {
for (ApplicationListener listener : getApplicationListeners(event)) {
if ((listener instanceof TransactionAware) && TransactionSynchronizationManager.isSynchronizationActive()) {
TransactionSynchronizationManager.registerSynchronization(
new EventTransactionSynchronization(listener, event));
}
else {
notifyEvent(listener, event);
}
}
}
void notifyEvent(final ApplicationListener listener, final ApplicationEvent event) {
Executor executor = getTaskExecutor();
if (executor != null) {
executor.execute(new Runnable() {
public void run() {
listener.onApplicationEvent(event);
}
});
}
else {
listener.onApplicationEvent(event);
}
}
class EventTransactionSynchronization extends TransactionSynchronizationAdapter {
private final ApplicationListener listener;
private final ApplicationEvent event;
EventTransactionSynchronization(ApplicationListener listener, ApplicationEvent event) {
this.listener = listener;
this.event = event;
}
@Override
public void afterCompletion(int status) {
if ((phase == TransactionPhase.AFTER_SUCCESS)
&& (status == TransactionSynchronization.STATUS_COMMITTED)) {
notifyEvent(listener, event);
}
}
}
}
這一切都是在春季通過註釋本機處理了。 請參閱https://spring.io/blog/2015/02/11/better-application-events-in-spring-framework-4-2https://spring.io/blog/2015/02/11/better特別是有關新的@TransactionalEventListener註釋的部分。 – PaulNUK 2015-12-16 08:15:32