Event Handling in Spring

Spring’s event handling is single-threaded so if an event is published, until and unless all the receivers get the message, the processes are blocked and the flow will not continue. Hence, care should be taken when designing your application if the event handling is to be used. Event publishing is one of the capabilities provided

Spring’s event handling is single-threaded so if an event is published, until and unless all the receivers get the message, the processes are blocked and the flow will not continue. Hence, care should be taken when designing your application if the event handling is to be used. Event publishing is one of the capabilities provided

Spring’s event handling is single-threaded so if an event is published, until and unless all the receivers get the message, the processes are blocked and the flow will not continue. Hence, care should be taken when designing your application if the event handling is to be used.

Event publishing is one of the capabilities provided by ApplicationContext.

There are a few simple guidelines to follow:

  • the event should extend ApplicationEvent
  • the publisher should inject an ApplicationEventPublisher object
  • the listener should implement the ApplicationListener interface

A Simple Application Event

Let’s create a simple event class – just a placeholder to store the event data. In this case, the event class holds a String message:

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

Now let’s create a publisher of that event. The publisher constructs the event object and publishes it to anyone who’s listening.

To publish the event, the publisher can simply inject the ApplicationEventPublisher and use the publishEvent() API:

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

    public void doStuffAndPublishAnEvent(final String message) {
        System.out.println("Publishing custom event. ");
        CustomSpringEvent customSpringEvent = new CustomSpringEvent(this, message);
        applicationEventPublisher.publishEvent(customSpringEvent);
    }
  }

A Listener

Finally, let’s create the listener. The only requirement for the listener is to be a bean and implement ApplicationListener interface:

@Component
public class CustomSpringEventListener implements ApplicationListener<CustomSpringEvent> {
    @Override
    public void onApplicationEvent(CustomSpringEvent event) {
        System.out.println("Received spring custom event - " + event.getMessage());
    }
}
Subscribe
Notify of
guest
0 Comments
Newest
Oldest Most Voted
Inline Feedbacks
View all comments