Spring has events that can help facility functionalities of your application such as sending emails, calling a third party API, or processing an event asynchronously. The design pattern publisher and subscribers is exactly what spring boot events are.
First, create a spring event
To create a spring event, your event class has to extend the spring ApplicationEvent class. Here is an example of UserCreateEvent.
public class UserCreateEvent extends ApplicationEvent {
private Logger log = LoggerFactory.getLogger(this.getClass());
public UserCreateEvent(User user) {
super(user);
log.info("UserCreateEvent, user={}", ObjectUtils.toJson(user));
}
}
Second, create a publisher
A publisher has to be a spring bean. A publisher has to have a ApplicationEventPublisher field. You can create a method to call the publishEvent method on the ApplicationEventPublish class. Here is an example of a publisher.
@Component
public class UserEventPublisher {
private Logger log = LoggerFactory.getLogger(this.getClass());
@Autowired
private ApplicationEventPublisher applicationEventPublisher;
public void processUserCreate(User user) {
UserCreateEvent userEvent = new UserCreateEvent(user);
log.info("processUserCreate, userEvent={}",ObjectUtils.toJson(userEvent));
applicationEventPublisher.publishEvent(userEvent);
}
}
Lastly, create a listener
A spring event listener must be a spring bean. Anotate the event listener with @EventListener. There can be multiple listeners for an event. Listeners are by default synchronous. You can make listeners asychronous by adding @Async the method. Here is an example of a spring event listener.
@Component
public class UserEventListener{
private Logger log = LoggerFactory.getLogger(this.getClass());
@Async
@EventListener
public void handleUserCreateEvent(UserCreateEvent createEvent) {
log.info("handleUserCreateEvent, event={}",ObjectUtils.toJson(createEvent));
}
}