我在这里使用 Axon & Spring 进行了相当简单的 CQRS 设置。
这是配置类。
@AnnotationDriven
@Configuration
public class AxonConfig {
@Bean
public EventStore eventStore() {
...
}
@Bean
public CommandBus commandBus() {
return new SimpleCommandBus();
}
@Bean
public EventBus eventBus() {
return new SimpleEventBus();
}
}
这是我的聚合...
@Aggregate
public class ThingAggregate {
@AggregateIdentifier
private String id;
public ThingAggregate() {
}
public ThingAggregate(String id) {
this.id = id;
}
@CommandHandler
public handle(CreateThingCommand cmd) {
apply(new ThingCreatedEvent('1234', cmd.getThing()));
}
@EventSourcingHandler
public void on(ThingCreatedEvent event) {
// this is called!
}
}
这是我在单独的 .java 文件中的 EventHandler ......
@Component
public class ThingEventHandler {
private ThingRepository repository;
@Autowired
public ThingEventHandler(ThingRepository thingRepository) {
this.repository = conditionRepository;
}
@EventHandler
public void handleThingCreatedEvent(ThingCreatedEvent event) {
// this is only called if I publish directly to the EventBus
// apply within the Aggregate does not call it!
repository.save(event.getThing());
}
}
我正在使用 CommandGateway 发送原始创建命令。我在聚合中的 CommandHandler 可以正常接收命令,但是当我apply
在聚合中调用时,传递一个新事件,我在外部类中的 EventHandler 不会被调用。只有直接在 Aggregate 类中的 EventHandlers 才会被调用。
如果我尝试将事件直接发布到 EventBus,则会调用我的外部 EventHandler。
知道为什么我在apply
聚合中调用时没有调用外部 java 类中的 EventHandler 吗?