Mastering Spring’s Event System: From Events to Listeners and Broadcasters

This article explains Spring's event mechanism, covering the ApplicationEvent API, built‑in events, listener registration via @EventListener, the internal processing flow, SimpleApplicationEventMulticaster broadcasting, and the specific event types and listeners used in Spring Boot.

Programmer DD
Programmer DD
Programmer DD
Mastering Spring’s Event System: From Events to Listeners and Broadcasters

Introduction

Spring's event mechanism consists of three core components: the event object, the listening method, and the broadcaster. This article explains each part in detail.

Spring Event

The base class for Spring events is ApplicationEvent, which extends java.util.EventObject. The constructor receives the event source.

public abstract class ApplicationEvent extends EventObject {
    // ... other code ...
    public ApplicationEvent(Object source) {
        super(source);
        this.timestamp = System.currentTimeMillis();
    }
    // ... other code ...
}

Built‑in Spring Events

ContextRefreshedEvent – Spring application context is ready.

ContextStartedEvent – Spring application context has started.

ContextStoppedEvent – Spring application context has stopped.

ContextClosedEvent – Spring application context has been closed.

Generic payload events can be created via PayloadApplicationEvent.

Spring Event Listening Methods

Two Listening Approaches

1. Implement ApplicationListener or annotate a method with @EventListener. The method can listen to one or many event types and supports generic events.

2. Add @Async to an @EventListener method to make it asynchronous; the method must return void.

@EventListener Internals

Finding the Entry Point

EventListener processing flow
EventListener processing flow

The class EventListenerMethodProcessor is the entry point that processes @EventListener annotations.

Core Logic

The processor scans bean classes for methods annotated with @EventListener, creates an ApplicationListenerMethodAdapter via an EventListenerFactory, and registers the listener with the application context.

private void processBean(final String beanName, final Class<?> targetType) {
    // ... omitted for brevity ...
    Map<Method, EventListener> annotatedMethods = MethodIntrospector.selectMethods(
        targetType, (MethodIntrospector.MetadataLookup<EventListener>) method ->
            AnnotatedElementUtils.findMergedAnnotation(method, EventListener.class));
    // ... register listeners ...
}

Only public methods can be used because AopUtils.selectInvocableMethod excludes private, static, or proxied methods.

Summary of @EventListener

EventListenerMethodProcessor implements SmartInitializingSingleton and registers listeners after all singletons are instantiated.

DefaultEventListenerFactory adapts @EventListener methods to ApplicationListener instances.

ApplicationListenerMethodAdapter is the concrete adapter class.

Spring’s Broadcaster

The broadcaster is ApplicationEventMulticaster, with the default implementation SimpleApplicationEventMulticaster. It maintains the association between events and listeners and dispatches events.

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

The method getApplicationListeners retrieves matching listeners based on event type and source, using an internal cache keyed by ListenerCacheKey (event type + source type).

SimpleApplicationEventMulticaster Summary

Manages ApplicationListener registration and event broadcasting.

Maintains a cache Map<ListenerCacheKey, ListenerRetriever> for efficient listener lookup.

Uses ListenerCacheKey composed of event type and source type.

Broadcasts events via multicastEvent methods.

Spring Boot Events

Spring Boot Event Types

ApplicationStartingEvent (since 1.5)

ApplicationEnvironmentPreparedEvent

ApplicationPreparedEvent

ApplicationStartedEvent

ApplicationReadyEvent (published after the context is ready)

ApplicationFailedEvent (published after a failure)

Spring Boot Event Listening

Listeners declared in META-INF/spring.factories under the ApplicationListener key.

Programmatically added via SpringApplication.addListeners(...) or SpringApplicationBuilder.listeners(...).

Spring Boot Broadcaster

Spring Boot uses its own SimpleApplicationEventMulticaster, which is separate from the one in Spring Framework after version 2.0.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

JavaEventspring-boot
Programmer DD
Written by

Programmer DD

A tinkering programmer and author of "Spring Cloud Microservices in Action"

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.