Skip to content

Spring Eventing

AlexanderKosmehl edited this page Jan 27, 2021 · 6 revisions

General Information

The following is a short guideline when you want to publish or receive events:

Publish Events

  • Create a custom event for your domain
  • Use @Autowired to get an instance of the base ApplicationEventPublisher which you can use to send the event using its .publishEvent method or implement your own, if you want to apply some transformations to the data

Listening to Events

  • Create a custom event listener for your domain
  • Make sure that the event listener accepts events of the specific type you want to receive
  • As soon as an event publisher sends an event of said type all corresponding onApplicationEvent methods gets triggered across all listeners

Code Examples

Custom Spring Event

public class CustomSpringEvent extends ApplicationEvent {
    private String message;

    public CustomSpringEvent(Object source, String message) {
        super(source);
        this.message = message;
    }
    public String getMessage() {
        return message;
    }
}

Custom events can be extended from the base ApplicationEvent. The type of the new event can be used in the subsequent EventPublisher and EventListener to check only for events of this type.


Custom Event Publisher

@Component
public class CustomSpringEventPublisher {
    @Autowired
    private ApplicationEventPublisher applicationEventPublisher;

    public void publishCustomEvent(final String message) {
        applicationEventPublisher.publishEvent(new CustomSpringEvent(this, message));
    }
}

A custom EventPublisher can be defined using the @Component annotation. Note that even a custom publisher uses the base ApplicationEventPublisher to send events. This means that you do not have to create a new publisher for every variation of event you attempt to send. You could even use the base publisher in the same way it is used here, just with different events. One reason you might want to create a custom publisher would rather be, that you want to apply some additional transformations to the event data before it is sent.


Custom Event Listener

@Component
public class CustomSpringEventListener implements ApplicationListener<CustomSpringEvent> {
    @Override
    public void onApplicationEvent(CustomSpringEvent event) {
        System.out.println("Received event: " + event.getMessage() + "\n");

        // Deserializing Message JSON
        Gson gson = new Gson();
        DemoJSON2 receivedJSON = gson.fromJson(event.getMessage(), DemoJSON2.class);
    }
}

Custom event listeners are defined using the base ApplicationListener class and the @Component annotation. A custom eventListener can be created to only listen for events of a specific type.

Clone this wiki locally