5

I want to build event processing based on event generic type.

Event class:

public class PushNotificationStoreEvent<T extends Push> extends ApplicationEvent {
    private static final long serialVersionUID = -3791059956099310853L;

    public T push;

    public PushNotificationStoreEvent(Object source, T push) {
        super(source);
        this.push = push;
    }
}

Here Push is marker interface for classes: PushNotificationNew and PushNotificationFail.

Listeners:

@Async
@EventListener
public void storeNewPush(PushNotificationStoreEvent<PushNotificationNew> event) {
    pushNewRepoService.save(event.push);
}
@Async
@EventListener
public void storeFailPush(PushNotificationStoreEvent<PushNotificationFail> event) {
    pushFailRepoService.save(event.push);
}

Problem: there is no distinction between PushNotificationStoreEvent<PushNotificationNew> and PushNotificationStoreEvent<PushNotificationFail> for listeners.

It means, that all events PushNotificationStoreEvent are processed by all listeners.

I can solve that by creating separate event class per case or use one listener and instanceof by event.push to choose right action. Maybe you know better solution?

Woland
  • 623
  • 2
  • 13
  • 31
  • Did you ever find a solution to this? I would like to avoid creating a cohort of classes like `PushNotificationStoreEventNew` and `PushNotificationStoreEventFail`, and use generic typed events like you describe here. – Michael Fulton Jan 07 '22 at 19:31
  • 1
    @MichaelFulton No, I've chosen one method and `instanceof` inside. – Woland Jan 10 '22 at 21:12

0 Answers0