2

I'm looking for a way to pass two arguments to an @EventListener. I have an Event class. It looks like this:

public class Event {
    String id;
    Date timestamp;
    String data;
    String type;
}

The data is serialized, and the type describes how to deserialize it.

Currently, I deserialize the event data, and then publish the deserialized EventData subclass instance on via an `ApplicationEventPublisher like so:

public void listen(Event event) throws IOException {
    EventData eventData = converter.toEventData(event);
    eventPublisher.publishEvent(eventData);        
} 

This has worked well so far, but now I need access to both the event and the data in my listeners. Is there a way to pass two arguments to an @EventListener?

Josh C.
  • 4,303
  • 5
  • 30
  • 51

1 Answers1

3

I don't thing there is a way you could pass a second argument to event listeners.

You could add an event property to the EventData base class that is populated by the converter with the original argument that is passed to it.

Constantin Galbenu
  • 16,951
  • 3
  • 38
  • 54
  • What about using a tuple? I'm not current with java, but is there a tuple class that everyone uses? – Josh C. Feb 13 '18 at 02:09
  • @JoshC. I thought that the event-dispatching is done by the class of the `EventData` so that should remain the same. I suppose that if you can/would modify all your listeners then you could use a tuple. – Constantin Galbenu Feb 13 '18 at 02:13
  • What is the typical tuple class? – Josh C. Feb 13 '18 at 03:07
  • Actually, I realized the problem is I need to dynamically create the tuple. EventData is the super class, but I need to broadcast the derived type to ensure delivery to the right handler. The tuple would need to be instantiated with that derived type. I think I'm going with the back reference on the EventData class... – Josh C. Feb 13 '18 at 15:27