我有这个存储库片段接口:
interface EntityEventObserver<T> {
void addCreatedListener(Consumer<CreatedEvent<T>> listener);
}
和实现:
class EntityEventObserverImpl<T> implements EntityEventObserver<T> {
@Override
public void addCreatedListener(Listener listener) { /* ... */ }
@EventListener
public void onCreated(CreatedEvent<T> event) { /* ... */ }
}
事件定义为:
class CreateEvent<T> extends ApplicationEvent implements ResolvableTypeProvider {
final T entity;
public CreatedEvent(T entity) {
super(entity);
this.entity = entity;
}
@Override
public ResolvableType getResolvableType() {
return ResolvableType.forClassWithGenerics(this.getClass(), ResolvableType.forInstance(this.entity));
}
}
最后,存储库:
interface FooRepository extends JpaRepository<Foo, Long>, EntityEventObserver<Foo> {}
interface BarRepository extends JpaRepository<Bar, Long>, EntityEventObserver<Bar> {}
每创建一个实体,CreatedEvent
就会以eventPublisher.publishEvent(new CreatedEvent<>(entity))
的形式发布。
使用这些类型,我希望
fooRepository.addCreatedListener(event -> /* ... */);
仅针对CreatedEvent<Foo>
个事件被调用,但是也被CreatedEvent<Bar>
个事件调用。
我想念什么?我如何才能仅调用正确的侦听器? SpEL魔术?