In Domain-Driven Design, a domain event records a business fact that has already happened, so we name it in the past tense, for example OrderPlaced. When the Order Service calls the Payment Service and the Shipping Service directly, it knows too much about its neighbours, and every new consumer forces a change in the order code. A domain event reverses this dependency: the Order aggregate only states what happened, and other bounded contexts decide for themselves how to react. The event is an immutable value object that carries only the data consumers need, such as the order id and the total, and never the whole aggregate. Keep in mind that most brokers deliver at least once, so every consumer must be idempotent, and you should store the event in the same transaction as the order (outbox pattern) to avoid lost messages.

Context of the example: the Order Service confirms an order, publishes OrderPlaced, and a listener in the Payment context reacts to it. Order does not import any payment class.

// Domain event: immutable, past tense, minimal data
public record OrderPlaced(UUID orderId, BigDecimal total, Instant occurredAt) {}
// Order Service: knows nothing about Payment
@Service
class PlaceOrderService {
private final OrderRepository orders;
private final ApplicationEventPublisher events;
PlaceOrderService(OrderRepository orders, ApplicationEventPublisher events) {
this.orders = orders;
this.events = events;
}
@Transactional
public void place(UUID orderId) {
Order order = orders.findById(orderId).orElseThrow();
order.confirm(); // aggregate enforces its own rules
orders.save(order);
events.publishEvent(new OrderPlaced(order.id(), order.total(), Instant.now()));
}
}
// Payment context: reacts after the order transaction commits
@Component
class PaymentListener {
@TransactionalEventListener
void on(OrderPlaced event) {
// create payment request for event.orderId() and event.total()
}
}

Schreibe einen Kommentar

I’m Iman

Mein Name ist Iman Dabbaghi. Ich arbeite als Senior Software Engineer in der Schweiz. Außerdem interessiere ich mich sehr für gewaltfreie Kommunikation, Bachata-Tanz und Musik sowie fürs die Persönlichkeitsentwicklung.

Ich habe einen Masterabschluss in Informatik von der Universität Freiburg in Deutschland, bin Spring/Java Certified Professional (OCP), Certified Professional for Software Architecture (CPSA-F) und ein lebenslanger Lernender 🎓.

EN:

My name is Iman Dabbaghi. I work as a Senior Software Engineer in Switzerland. I am also very interessted in nonviolent communication, Bachata dance and music and also for personal development.

I hold a masters degree in computer science from the university of Freiburg in Germany, am a Spring / Java Certified Professional (OCP), Certified Software Architecture (CPSA-F) and Life Long Learner🎓

Let’s connect