lebronjamesuit / event-driven-products

Using Axon Framework to build a small backend for an microservice ecommerce app. Style of coding is Domain-driven design (DDD) & Event-driven architecture
2 stars 0 forks source link

@CommandHandler on constuctors or methods #9

Open lebronjamesuit opened 1 year ago

lebronjamesuit commented 1 year ago

Is Event Store must be looking for @CommandHandler on the aggregate class, constructor for the very first one to initiated properly the aggregate before it started looking for others methods with the mark @CommandHandler. Why is that?

lebronjamesuit commented 1 year ago

Using a Constructor Command Handler will make sure Axon Framework creates a new Aggregate for you! Usually there is no business logic here, you just create it, you apply an Event which will be handled by your Event Sourcing Handler and after that (not going into UoW here), that Event is stored on your Event Store.

Using a Command Handler method, Axon Framework will, based on the @TargetAggregateIdentifier field of your Command, try to load that specific Aggregate before applying the new Command. If you Aggregate does not exist, it will throw an Exception. Also, usually you have business logic in your Command Handler methods in this case.

I would like to add to the second case the AggregateCreationPolicy 1, which is something new that you can use to annotate your CommandHandler and give it “special powers”. In this example, we would be interested in the @CreationPolicy(AggregateCreationPolicy.CREATE_IF_MISSING) which will tell your method to Create an Aggregate if it can’t find one on your Event Store. Of course this is a costy operation since you will have to look for that Aggregate on your Event Store without knowing if you will find it or not - in that case, I would avoid it and only use if there is a specific use case for that.

Another note, DDD is all about being explicity. So using a constructor to create an Aggregate is the best approach.