Observer
- Intent
- Define a one-to-many dependency so that when one object changes, everyone interested hears about it without that object knowing them.
- Application
- A personal record has to notify the athlete, update the leaderboard and hand out a badge. Publish one event and let each part react on its own, without the service knowing who's listening.
The athlete sends 105 kg to LiftController, which calls CoupledResultService, highlighted in red; it calls Notifier, Leaderboard and Badges directly.
The award() ✗ packet goes from CoupledResultService to Badges, highlighted: the call fails.
ManualPrSubject and the PrObserver interface appear, highlighted; two observers, the leaderboard one and the badges one, implement it and the subject sends onRecord() to the interface.
The Spring context appears with ResultService and ApplicationEventPublisher, highlighted together with the context, wired to the three listeners.
The three listeners, NotificationListener, LeaderboardListener and BadgeListener, appear highlighted.
105 kg travels from the athlete to the controller, record() to ResultService, highlighted, PR event to the publisher and from there to LeaderboardListener and BadgeListener.
The event goes from the service to the publisher and an exception comes back from BadgeListener, highlighted, to the publisher.
The event travels from the publisher to NotificationListener, highlighted, which handles it on another thread.
Inside the Spring context, ApplicationContext, highlighted, sends ContextRefreshedEvent to the event publisher, also highlighted.
Final view: the athlete, the controller, ResultService and the event publisher handing the PR to the three listeners, all inside the Spring context.
Step 1 of 10
One PR that sets everything off
Ana just back-squatted 105 kg, five more than her best. A personal record means three things:
- Notify her with a message.
- Update the leaderboard for that lift.
- Give her the badge "PR club".
In the coupled version, CoupledResultService does all three by calling each service directly, one after another.
Step 2 of 10
If the badge fails, the PR is lost
The badge service is down and award() throws. Since everything happens in the same method, the best.put(...) on the next line never runs: Ana's PR isn't stored.
The example test proves it. A side feature (a badge) has taken down the main one (recording the result).
Step 3 of 10
Observer: announce, don't call
The Observer pattern flips the relationship:
PrObserveris the contract:onRecord(event).- Each interested party implements it in its own way.
ManualPrSubjectkeeps a list of observers, lets them sign up withsubscribe()and, when there's a PR, walks the list and tells each one.
The subject no longer knows whether there's one, three or none, or what each one does.
Step 4 of 10
The context already is a publisher
You don't need to write the subscriber list: the Spring context already has one. ResultService gets an ApplicationEventPublisher and, when it detects a PR, does:
events.publishEvent(new PersonalRecordEvent(...))
And that's it. No fields for notifications, leaderboard or badges.
Step 5 of 10
Listening is an annotation
Every interested party is a bean with an @EventListener method that takes the event type it cares about:
LeaderboardListenerupdates the leaderboard.BadgeListenerhands out the "PR club" badge.NotificationListenerprepares the "new PR" message.
Spring finds them at startup and subscribes them on its own, with no interfaces and no manual registration.
Step 6 of 10
A PR start to finish
Ana logs her 105 kg:
POST /api/liftsreaches the controller, which callsrecord().ResultServicestores the new mark and sees it beats the previous 100 kg.- It publishes a
PersonalRecordEvent. - The leaderboard shows Ana at 105 kg, she gets the badge, and the message "new PR in Back squat, 105 kg (+5)" goes out.
Step 7 of 10
Careful: it's synchronous
A detail that surprises people: by default publishEvent() calls each listener on the same thread, one after another, and doesn't return until they're done.
So if a listener throws, the publisher gets the exception. The example test uses a broken badge printer and record() fails along with it.
Careful, because step 2's problem isn't completely gone. The mark is already stored (the event is published afterwards), but the POST answers 500, the listeners after the broken one don't run and, if the athlete retries, it no longer counts as a PR.
Step 8 of 10
The slow stuff, on another thread
Sending a notification is slow: there's a network and an external service involved. With @Async on the listener (and @EnableAsync on the application), Spring hands it the event on another thread, and record() answers without waiting for it.
Step 9 of 10
Spring already does it for you
Spring talks to itself this way. The ApplicationContext publishes ContextRefreshedEvent at startup and ContextClosedEvent on shutdown, and Spring Boot adds ApplicationReadyEvent, WebServerInitializedEvent… Your code hooks in with the same @EventListener.
Step 10 of 10
Recap
You started with a service that called everyone and ended up with:
- One event,
PersonalRecordEvent, published in one line. - Independent listeners, each with its own
@EventListener. - Synchronous by default, with
@Asyncor@TransactionalEventListenerwhen you need them, knowing where errors go in each case. - Zero coupling: adding a reaction doesn't touch the service.
Code
CoupledResultService.java
public boolean record(LiftResult r) {
var key = new Key(r.athlete(), r.lift());
boolean pr = r.kg() > best.getOrDefault(key, 0);
if (pr) {
notifier.send(r.athlete() + ": new PR!"); // one more line for every new feature...
leaderboard.update(r.lift(), r.athlete(), r.kg());
badges.award(r.athlete(), "PR club"); // ...and if this one throws, nothing below runs
best.put(key, r.kg());
}
return pr;
}CoupledResultService.java
public boolean record(LiftResult r) {
var key = new Key(r.athlete(), r.lift());
boolean pr = r.kg() > best.getOrDefault(key, 0);
if (pr) {
notifier.send(r.athlete() + ": new PR!"); // one more line for every new feature...
leaderboard.update(r.lift(), r.athlete(), r.kg());
badges.award(r.athlete(), "PR club"); // ...and if this one throws, nothing below runs
best.put(key, r.kg());
}
return pr;
}ManualPrSubject.java
private final List<PrObserver> observers = new ArrayList<>();
public void subscribe(PrObserver observer) {
observers.add(observer);
}
public boolean record(LiftResult r) {
var key = new Key(r.athlete(), r.lift());
Integer previous = best.get(key);
boolean pr = previous == null || r.kg() > previous;
if (pr) {
best.put(key, r.kg());
var event = new PersonalRecordEvent(r.athlete(), r.lift(), r.kg(), previous);
for (PrObserver o : observers) {
o.onRecord(event); // the subject only knows the interface
}
}
return pr;
}ResultService.java
public boolean record(LiftResult r) {
Integer previous = keepBest(r);
boolean pr = previous == null || r.kg() > previous;
if (pr) {
// announce it and move on: who reacts is none of this class's business
events.publishEvent(new PersonalRecordEvent(r.athlete(), r.lift(), r.kg(), previous));
}
return pr;
}LeaderboardListener.java
@EventListener
public void on(PersonalRecordEvent e) {
byLift.computeIfAbsent(e.lift(), lift -> new ConcurrentHashMap<>()).merge(e.athlete(), e.kg(), Math::max);
}ResultServiceTest.java
boolean pr = results.record(new LiftResult("Ana", "Back squat", 105));
assertThat(pr).isTrue();
assertThat(leaderboard.top("Back squat")).containsEntry("Ana", 105);
assertThat(badges.badgesOf("Ana")).contains("PR club");
// notifications run @Async, on another thread: wait for ours to arrive
assertThat(nextMessageLike("Ana: new PR in Back squat, 105")).isEqualTo("Ana: new PR in Back squat, 105 kg (+5)");SyncByDefaultTest.java
// @EventListener runs on the same thread, during publishEvent():
// a failing listener makes record() itself fail
assertThatThrownBy(() -> results.record(new LiftResult("Ana", "Snatch", 60)))
.isInstanceOf(IllegalStateException.class)
.hasMessage("badge printer out of ink");NotificationListener.java
@Async // slow I/O: run it on another thread so record() doesn't wait for it
@EventListener
public void on(PersonalRecordEvent e) {
String delta = e.previousKg() == null ? "first" : "+" + (e.kg() - e.previousKg());
String message = e.athlete() + ": new PR in " + e.lift() + ", " + e.kg() + " kg (" + delta + ")";
while (!sent.offer(message)) sent.poll(); // full: drop the oldest
}SpringDoesItTooTest.java
static class BoxOpening {
@EventListener(ContextRefreshedEvent.class)
void doorsOpen() {
heard.add("context ready: warm up the rower displays");
}
@EventListener(ContextClosedEvent.class)
void doorsClose() {
heard.add("context closing: save today's leaderboard");
}
}ResultService.java
public boolean record(LiftResult r) {
Integer previous = keepBest(r);
boolean pr = previous == null || r.kg() > previous;
if (pr) {
// announce it and move on: who reacts is none of this class's business
events.publishEvent(new PersonalRecordEvent(r.athlete(), r.lift(), r.kg(), previous));
}
return pr;
}