I have a AbstractBaseEntity
which inherits from org.springframework.data.domain.AbstractAggregateRoot
.
My entity Purchase
inherits from this base entity and registers an event, before a new entity is persisted. (But not when it is updated.)
@PrePersist
public void createPersistEvent() {
this.registerEvent(new DomainEvent(this));
}
This works fine, but now I listen to the fired events with this listener
@Component
@RequiredArgsConstructor
class PurchaseEventHandler {
private final PurchaseRepository purchaseRepository;
@TransactionalEventListener(phase = TransactionPhase.AFTER_COMMIT)
@Transactional(propagation = Propagation.REQUIRES_NEW)
public void onEvent(DomainEvent event) {
//...
}
}
which catches the event.
When debugging, I see that eventually after @PrePersist
a new entity of Purchase
is created. And AbstractAggregateRoot#domainEvents()
is only called on this new instance and then returns an empty list. On the first instance, AbstractAggregateRoot#domainEvents()
is never called.
All I want is to receive an event when a new instance of Purchase
was successfully created and persisted in the database. This should happen async after the transaction was completed. What is the right way to go?