Spring event publishing and monitoring instance



This article mainly introduces how to publish time and receive events in spring

Define events

public class DemoEvent extends ApplicationEvent {
    private String message;

    public DemoEvent(Object source, String message) {
        this.message = message;
    public String getMessage() {
        return message;

Publish event

    private ApplicationEventPublisher applicationEventPublisher;

    public Object sendEvent(@RequestParam String msg){
        DemoEvent demoEvent = new DemoEvent(this,msg);
        LOGGER.info("finish publish event");
        return "success";

This is released in mvc for demonstration only.

Receive events (Default synchronization)

public class DemoEventListener implements ApplicationListener<DemoEvent>{

    private static final Logger LOGGER = LoggerFactory.getLogger(DemoEventListener.class);

    public void onApplicationEvent(DemoEvent demoEvent) {
        LOGGER.info("receive event:{}",demoEvent.getMessage());

This is synchronous reception

Asynchronous handling of events

public class AsyncEventConfig {

    @Bean(name = "applicationEventMulticaster")
    public ApplicationEventMulticaster simpleApplicationEventMulticaster() {
        SimpleApplicationEventMulticaster eventMulticaster
                = new SimpleApplicationEventMulticaster();

        eventMulticaster.setTaskExecutor(new SimpleAsyncTaskExecutor());
        return eventMulticaster;

Add this configuration and you’ll be ok. Otherwise, note that if you want to gracefully shutdown your new task executor, you need to shut down yourself.


spring-context-4.3.11.RELEASE-sources.jar! /org/springframework/context/event/SimpleApplicationEventMulticaster.java

    public void multicastEvent(ApplicationEvent event) {
        multicastEvent(event, resolveDefaultEventType(event));

    public void multicastEvent(final ApplicationEvent event, ResolvableType eventType) {
        ResolvableType type = (eventType != null ? eventType : resolveDefaultEventType(event));
        for (final ApplicationListener<?> listener : getApplicationListeners(event, type)) {
            Executor executor = getTaskExecutor();
            if (executor != null) {
                executor.execute(new Runnable() {
                    public void run() {
                        invokeListener(listener, event);
            else {
                invokeListener(listener, event);

    private ResolvableType resolveDefaultEventType(ApplicationEvent event) {
        return ResolvableType.forInstance(event);

It can be seen that when using ApplicationEventMulticast, if there is a thread pool, the thread pool is used for asynchronous execution. Otherwise, it is known that the execution method directly calling listener is executed synchronously.