EventBus: Concept Overview
|
We used Guava’s EventBus in the past, but now we use Spring Event for better integration with the Spring ecosystem. In addition, Guava’s EventBus is deprecated and the maintainers themselves recommend using other implementations. |
The Spring Events, part of the Spring, implements a publish-subscribe (pub-sub) messaging pattern. This design pattern decouples the components that send events (publishers) from those that handle them (subscribers).
1. 🔁 Core Concept
Spring Events allows objects to communicate with each other without being tightly coupled. Instead of directly calling methods on other objects, an object can post an event to the EventBus, and any object that is annotated as a listener to that type of event will automatically receive it.
2. 🧠 Key Features
-
Decoupling: Publishers don’t need to know who the subscribers are.
-
Type-based routing: Events are dispatched to subscribers based on the event’s type.
-
Annotation-driven: Methods that should handle events are annotated with
@EventListener. -
Thread-safe: Internally synchronized so that multiple threads can safely post events or register subscribers.
-
Synchronous by default: Event handlers are called in the same thread as the caller that posts the event (can be made async with
AsyncEventBus).
3. 🧱 Basic Components
3.1. 1. EventBus Instance
EventBus eventBus = new SpringEventBus();
3.2. 2. Event Class
@Builder
@AllArgsConstructor
@Getter
public class UserCreatedEvent {
private final String username;
}
3.3. 3. Subscriber
public class UserEventListener {
@EventListener
public void handleUserCreated(UserCreatedEvent event) {
System.out.println("Identity created: " + event.getUsername());
}
}
3.4. 4. Posting an Event
eventBus.register(new UserEventListener());
eventBus.publishEvent(new UserCreatedEvent("Alice"));
4. ⚡ Use Cases
-
Event-driven applications
-
UI updates in response to model changes
-
Decoupling business logic from controllers or services
-
In-process communication within complex systems