Spring Framework — Application Events (Synchronous)

Spring application events have been part of the Spring Framework from the beginning. The application events of the spring framework is an implementation of the Observer pattern. The Observer pattern serves as a means to exchange information between loosely coupled components.

1. Multi-part Series

2. Application Events — Synchronous

The application event capability of the Spring framework is synchronous by default. This implies the publisher method blocks until all registered listeners have processed the event.

2.1 Application Event — MessageEvent

The ApplicationEvent class is abstract since it doesn’t make sense for generic events to be published directly.

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

Javadoc

2.2 Event Publisher — SpringEventPublisher

The SpringEventPublisher publish the MessageEvent which notifies all matching listeners registered with this application of an application event.

The publication of the event is effectively a hand-off to the multicaster and does not imply synchronous/asynchronous execution or even immediate execution at all.

@Component
public class SpringEventPublisher {
private static final Logger logger = LoggerFactory.getLogger(SpringEventPublisher.class); @Autowired
private ApplicationEventPublisher applicationEventPublisher;
public void publishBasicEvent(final String message) {
logger.info("SpringEventPublisher: Publish Event Started.");
MessageEvent basicSpringEvent = new MessageEvent(this, message);
applicationEventPublisher.publishEvent(basicSpringEvent);
logger.info("SpringEventPublisher: Publish Event Complete.");
}
}

Javadoc

2.3 Event Listener — SynchronousEventListener

The onApplicationEvent handles the application event, which in this case is the MessageEvent. The Listener has access to the event data via the accessor method of the message property.

@Component
public class SynchronousEventListener implements ApplicationListener<MessageEvent> {
private static final Logger logger = LoggerFactory.getLogger(SynchronousEventListener.class); @Override
public void onApplicationEvent(MessageEvent basicEvent) {
logger.info("SynchronousEventListener: Receive Event: "+ basicEvent.getMessage());
}
}

Javadoc

3. Example Code

4. Summary

Follow me on any of the different social media platforms and feel free to leave comments.