I am actually new in CQRS and Event Sourcing.
I got confused by Command Handler in Aggregate, when i saw this code :
@AllArgsConstructor
@NoArgsConstructor
@Getter
@Aggregate
public class BankAccountAggregate {
@AggregateIdentifier
private UUID id;
private BigDecimal balance;
private String owner;
@CommandHandler
public BankAccountAggregate(CreateAccountCommand command){
AggregateLifecycle.apply(
new AccountCreatedEvent(
command.getAccountId(),
command.getInitialBalance(),
command.getOwner()
)
);
}
that command handler is just publishing an event. as you can see the naming of the object is AccountCreatedEvent but it doesn't mean the Account is created right?
the account creation is in EventHandler that subscribe AccountCreatedEvent :
@Slf4j
@RequiredArgsConstructor
@Component
public class BankAccountProjection {
private final BankAccountRepository repository;
private final QueryUpdateEmitter updateEmitter;
@EventHandler
public void on(AccountCreatedEvent event) throws Exception {
log.debug("Handling a Bank Account creation command {}", event.getId());
BankAccount bankAccount = new BankAccount(
event.getId(),
event.getOwner(),
event.getInitialBalance()
);
this.repository.save(bankAccount);
Boolean isActive = AggregateLifecycle.isLive();
}
}
What i know is :
- Event is something that has happened.
- Command is something we want to happen.
So why not we put the logic of Account creation in the Command Handler? what is the purpose of doing this?
full source code at this link.
