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 datapublic record OrderPlaced(UUID orderId, BigDecimal total, Instant occurredAt) {}// Order Service: knows nothing about Payment@Serviceclass 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@Componentclass PaymentListener { @TransactionalEventListener void on(OrderPlaced event) { // create payment request for event.orderId() and event.total() }}

Schreibe einen Kommentar