Injecting dependencies into Aggregates with Spring

Hey there,

Up until now, I haven’t had any problems with stuff injected from Spring’s context into my aggregate.
However, in the following scenario dependencies are not injected yet. Looks like maybe the Spring Aggregate Factory is not being used to instantiate the Aggregate in that scenario?

class MyAggregate {
private MyService myService;

constructor(MyCommand command) {
AggregateLifecycle.apply(new CreatedEvent(…))

private void onEvent(CreatedEvent event) {
// myService here is null

Any suggestions on best practises?


If you are trying to invoke business logic, I would move that to a seperate class. Methods annotated with @EventSourcingHandler are really intended to be used only for setting the state on an Aggregate.

As for injecting dependencies, I have been able to inject them as method parameters.


It’s not so much a business logic as creating an aggregate member and passing down some dependencies in the constructor to it, as it’s not Spring managed.

Hi Konrad,

because your command handler in this case is the contructor, Spring will never get a chance to inject these fields. As Ben suggested, you can add the Service as a parameter to either your CommandHandler or Event(Sourcing)Handler. Axon will inject it for you.