Axon Saga what is the purpose of SagaLifecycle.associateWith

44 Views Asked by At

I'm trying to wrap my head around the Saga pattern of Axon framework.

Given this block of code:

public class OrderManagementSaga {

    private boolean paid = false;
    private boolean delivered = false;
    @Inject
    private transient CommandGateway commandGateway;

    @StartSaga
    @SagaEventHandler(associationProperty = "orderId")
    public void handle(OrderCreatedEvent event) {
        // client generated identifiers
        ShippingId shipmentId = createShipmentId();
        InvoiceId invoiceId = createInvoiceId();
        // associate the Saga with these values, before sending the commands
        associateWith("shipmentId", shipmentId);
        associateWith("invoiceId", invoiceId);
        // send the commands
        commandGateway.send(new PrepareShippingCommand(...));
        commandGateway.send(new CreateInvoiceCommand(...));
    }

    @SagaEventHandler(associationProperty = "shipmentId")
    public void handle(ShippingArrivedEvent event) {
        delivered = true;
        if (paid) { end(); }
    }

    @SagaEventHandler(associationProperty = "invoiceId")
    public void handle(InvoicePaidEvent event) {
        paid = true;
        if (delivered) { end(); }
    }

    // ...
}

The document say about @SagaEventHandler(associationProperty = "orderId"):

For example, consider an incoming Event with a method "String getOrderId()", which returns "123". If a method accepting this Event is annotated with @SagaEventHandler(associationProperty="orderId"), this Event is routed to all Sagas that have been associated with an AssociationValue with key "orderId" and value "123".

So there will be a lot of Saga instances, and associationProperty="orderId" will be used to match an Event to a Saga. So far so good.

But what is the purpose of SagaLifecycle.associateWith("paymentId", paymentId);? The document does not give an example like the case @SagaEventHandler(associationProperty = "orderId"). I still not understand it, please help

0

There are 0 best solutions below