Newbie question about EventSourcedAggregateRoot objects

We are looking at Axon and saw the following pattern applied in more than one sample application. This snippet below is from the AddressBook sample in the axon github repo.

// In
Contact contact = new Contact(contactId, command.getNewContactName());

// In
public Contact(String identifier, String name) {
apply(new ContactCreatedEvent(identifier, name));

// In
protected void handleContactCreatedEvent(ContactCreatedEvent event) { = event.getContactId();

The id of the aggregate root is set when handling the ContactCreatedEvent as opposed to being done in the constructor. This seems a bit counter-intuitive and also dangerous. Surely we are missing something here. Can someone who is more knowledgeable with the framework kindly clarify?


Hi Prem,

This is actually the best way to do it, when using event sourcing. The identifier of the aggregate is state (although immutable) of the aggregate. Axon will actually assert that the identifier has been set by the very first event that was applied.

If you would set it in the constructor, the identifier would not be set when the aggregate is built up from its past events.

Hope this clarifies things.



Thanks very much for the clarification. It turns out that I needed to read more of the documentation. Also, I understand using the @EventSourcingHandler (instead of @EventHandler) inside the aggregate is the preferred way when handling domain events inside aggregates.