You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@grails.apache.org by ja...@apache.org on 2026/05/27 13:44:50 UTC

(grails-static-website) branch add-grails-transactional-events-v8 created (now c8a52de62d6)

This is an automated email from the ASF dual-hosted git repository.

jamesfredley pushed a change to branch add-grails-transactional-events-v8
in repository https://gitbox.apache.org/repos/asf/grails-static-website.git


      at c8a52de62d6 Add grails-transactional-events v8 guide

This branch includes the following new commits:

     new c8a52de62d6 Add grails-transactional-events v8 guide

The 1 revisions listed above as "new" are entirely new to this
repository and will be described in separate emails.  The revisions
listed as "add" were already present in the repository and have only
been added to this reference.



(grails-static-website) 01/01: Add grails-transactional-events v8 guide

Posted by ja...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

jamesfredley pushed a commit to branch add-grails-transactional-events-v8
in repository https://gitbox.apache.org/repos/asf/grails-static-website.git

commit c8a52de62d69a2a4c7188cfc5f59b98e9369fe05
Author: James Fredley <ja...@users.noreply.github.com>
AuthorDate: Wed May 27 09:44:36 2026 -0400

    Add grails-transactional-events v8 guide
    
    Cross-domain business logic in Grails using Spring application events
    with @TransactionalEventListener(AFTER_COMMIT). The pattern works
    out-of-the-box with GORM because GORM rides on Spring's
    PlatformTransactionManager: AFTER_COMMIT listeners fire when (and only
    when) the publisher's transaction commits, and are silently skipped on
    rollback.
    
    Sample-app-flavour Grails 8 guide that walks through:
    
    - An OrderService that publishes an OrderPlacedEvent POGO from a
      @Transactional method via ApplicationEventPublisher.
    - Three independent listeners (CustomerLifetimeValueListener,
      AuditListener, NotificationListener) wired purely by Spring
      @TransactionalEventListener annotations on grails-app/services/
      beans.
    - An @Async + @TransactionalEventListener composition for off-thread
      dispatch, with @EnableAsync wiring on the Application class.
    - A reference table of all four TransactionPhase values
      (BEFORE_COMMIT, AFTER_COMMIT, AFTER_ROLLBACK, AFTER_COMPLETION).
    - A side-by-side contrast with GORM domain-class lifecycle callbacks
      and Grails' @Subscriber / @Listener annotations.
    - A Spock @Integration spec that opens its own committed and
      rolled-back transactions to prove the AFTER_COMMIT contract.
    
    Registry entry added to conf/guides.yml with the standard v8 sample-app
    shape (sourcePath, tags, sampleRef pointing at
    grails-guides/grails-transactional-events grails8 branch, full toc).
    
    ./gradlew validateGuides -PvalidationMode=both passes (94 guides, 0
    errors). ./gradlew renderGuide_grails_transactional_events_8 renders
    all 17 chapters with every include:: directive resolved.
    
    Assisted-by: claude-code:claude-opus-4-7
---
 conf/guides.yml                                    | 59 +++++++++++++++
 .../v8/guide/asyncDispatch.adoc                    | 58 +++++++++++++++
 .../v8/guide/createApp.adoc                        | 11 +++
 .../v8/guide/domainModel.adoc                      | 32 +++++++++
 .../v8/guide/download.adoc                         | 14 ++++
 .../v8/guide/eventClass.adoc                       | 19 +++++
 .../v8/guide/gettingStarted.adoc                   |  5 ++
 .../v8/guide/helpWithGrails.adoc                   |  1 +
 .../v8/guide/howto.adoc                            | 10 +++
 .../v8/guide/integrationTest.adoc                  | 27 +++++++
 .../v8/guide/multipleListeners.adoc                | 21 ++++++
 .../v8/guide/publishingEvents.adoc                 | 19 +++++
 .../v8/guide/requirements.adoc                     |  5 ++
 .../v8/guide/theProblem.adoc                       | 21 ++++++
 .../v8/guide/transactionPhases.adoc                | 39 ++++++++++
 .../v8/guide/transactionalListener.adoc            | 21 ++++++
 .../v8/guide/vsGormEvents.adoc                     | 41 +++++++++++
 .../v8/guide/whatYouWillBuild.adoc                 | 12 ++++
 .../grails-app/domain/example/AuditLog.groovy      | 25 +++++++
 .../grails-app/domain/example/Customer.groovy      | 23 ++++++
 .../grails-app/domain/example/Order.groovy         | 23 ++++++
 .../grails-app/init/example/BootStrap.groovy       | 13 ++++
 .../services/example/AuditListener.groovy          | 30 ++++++++
 .../example/CustomerLifetimeValueListener.groovy   | 27 +++++++
 .../services/example/NotificationListener.groovy   | 37 ++++++++++
 .../services/example/OrderService.groovy           | 31 ++++++++
 .../example/OrderServiceIntegrationSpec.groovy     | 83 ++++++++++++++++++++++
 .../groovy/example/events/OrderPlacedEvent.groovy  | 18 +++++
 28 files changed, 725 insertions(+)

diff --git a/conf/guides.yml b/conf/guides.yml
index b1e98e996b9..2a7d994751c 100644
--- a/conf/guides.yml
+++ b/conf/guides.yml
@@ -4659,6 +4659,65 @@ guides:
           helpWithGrails:
             title: Do you need help with Grails?
 
+  - name: 'grails-transactional-events'
+    title: 'Cross-Domain Logic in Grails with Transactional Spring Events'
+    subtitle: 'Fan out business logic across multiple domains after a domain object changes state, using Spring ApplicationEventPublisher and @TransactionalEventListener(AFTER_COMMIT) - the pattern that just works with GORM because GORM rides on Spring''s PlatformTransactionManager.'
+    authors:
+      - 'James Fredley'
+    category: 'Grails Async'
+    publicationDate: '2026-05-27'
+    versions:
+      '8':
+        sourcePath: guides/grails-transactional-events/v8
+        publicationDate: '2026-05-27'
+        tags:
+          - 'events'
+          - 'event-publishing'
+          - 'async'
+          - 'transactional'
+          - 'spring-events'
+          - 'spring-boot'
+          - 'gorm'
+          - 'service-layer'
+          - 'services'
+          - 'domain-classes'
+          - 'integration-tests'
+          - 'testing'
+        sampleRef:
+          repo: 'grails-guides/grails-transactional-events'
+          branch: 'grails8'
+        toc:
+          gettingStarted:
+            title: Getting Started
+            whatYouWillBuild: What You Will Build
+            requirements: What You Will Need
+            howto: How to Complete the Guide
+          theProblem:
+            title: The Missing Pattern
+          createApp:
+            title: Creating the Application
+            download: Download a Grails 8 Starter
+          domainModel:
+            title: The Customer, Order, and AuditLog Domain Model
+          eventClass:
+            title: The OrderPlacedEvent POGO
+          publishingEvents:
+            title: Publishing Events From a Transactional Service
+          transactionalListener:
+            title: The First @TransactionalEventListener
+          transactionPhases:
+            title: The Four TransactionPhase Values
+          multipleListeners:
+            title: Fanning Out - A Second Listener
+          asyncDispatch:
+            title: Off-Thread Dispatch With @Async
+          vsGormEvents:
+            title: vs. GORM Lifecycle Callbacks and @Subscriber
+          integrationTest:
+            title: Proving the Contract With an Integration Spec
+          helpWithGrails:
+            title: Do you need help with Grails?
+
   - name: 'grails-tvmlapp'
     title: 'Build a TVML App with Grails'
     subtitle: 'Build an app for Apple TV with Grails. Leverage markup views, asset-pipeline and internazionalization capabilities of Grails to streamline TVML development'
diff --git a/guides/grails-transactional-events/v8/guide/asyncDispatch.adoc b/guides/grails-transactional-events/v8/guide/asyncDispatch.adoc
new file mode 100644
index 00000000000..6a3ac1edd51
--- /dev/null
+++ b/guides/grails-transactional-events/v8/guide/asyncDispatch.adoc
@@ -0,0 +1,58 @@
+The third listener stands in for "send a confirmation email" - exactly the kind of side-effect you don't want to do on the caller's thread. Composing `@Async` with `@TransactionalEventListener` hands the listener body to Spring's task executor *after* the commit lands.
+
+[source,groovy]
+.grails-app/services/example/NotificationListener.groovy
+----
+include::../snippets/grails-app/services/example/NotificationListener.groovy[]
+----
+
+Two pieces of wiring this listener needs:
+
+`@EnableAsync` somewhere in your Spring configuration. The typical home is the `Application` class:
+
+[source,groovy]
+.grails-app/init/example/Application.groovy
+----
+package example
+
+import grails.boot.GrailsApp
+import grails.boot.config.GrailsAutoConfiguration
+import grails.plugins.metadata.PluginSource
+import org.springframework.scheduling.annotation.EnableAsync
+
+@PluginSource
+@EnableAsync
+class Application extends GrailsAutoConfiguration {
+    static void main(String[] args) {
+        GrailsApp.run(Application, args)
+    }
+}
+----
+
+Without `@EnableAsync`, the `@Async` annotation is silently a no-op and the listener runs on the publisher's thread.
+
+The composition order with `@TransactionalEventListener` is exact:
+
+. The publisher's transaction commits.
+. Spring's `TransactionSynchronizationManager` fires the AFTER_COMMIT callback.
+. The callback dispatches the event to listener method references.
+. Because this listener method is also `@Async`, the call is handed to the `taskExecutor` bean instead of running on the synchronization thread.
+. The executor thread invokes `onOrderPlaced(...)` with no inherited transaction context.
+
+The "no inherited transaction context" point is important. If the async listener needs database access, it must open its own transaction with `@Transactional(propagation = REQUIRES_NEW)` on the listener method, exactly like the `CustomerLifetimeValueListener` did. Forgetting this and writing GORM code directly in an `@Async` listener body produces an enigmatic `org.hibernate.HibernateException: No Session found for current thread` from a stack frame that has nothing else to do with persistence.
+
+A few footguns:
+
+* *Exception handling is detached.* Exceptions thrown from an async listener don't reach the publisher. They land in Spring's `AsyncUncaughtExceptionHandler` (default: log at WARN). For listeners that drive critical infrastructure, install an explicit handler.
+* *Return values are detached.* Don't return a value from an async listener expecting Spring to publish it as a follow-up event - that mechanism (`@EventListener` returning a value to be auto-published) does not compose with async dispatch. Inject `ApplicationEventPublisher` and call `publishEvent(...)` explicitly if you need a follow-up event.
+* *Thread-pool tuning matters.* The default `taskExecutor` is sized for development. For production, declare a `ThreadPoolTaskExecutor` bean with a bounded queue and a sensible rejection policy - otherwise a burst of orders can pile up an unbounded queue of pending notification work.
+
+References:
+
+* link:https://docs.spring.io/spring-framework/docs/6.2.x/javadoc-api/org/springframework/context/event/EventListener.html[`@EventListener` javadoc - "Asynchronous Listeners" section]
+* link:https://docs.spring.io/spring-framework/docs/6.2.x/javadoc-api/org/springframework/scheduling/annotation/EnableAsync.html[`@EnableAsync` javadoc]
+
+Files touched in this chapter:
+
+* `grails-app/services/example/NotificationListener.groovy`
+* `grails-app/init/example/Application.groovy` (add `@EnableAsync`)
diff --git a/guides/grails-transactional-events/v8/guide/createApp.adoc b/guides/grails-transactional-events/v8/guide/createApp.adoc
new file mode 100644
index 00000000000..f3c21920b62
--- /dev/null
+++ b/guides/grails-transactional-events/v8/guide/createApp.adoc
@@ -0,0 +1,11 @@
+Start from a vanilla Grails 8 application. The default `web` profile with the H2 in-memory database is enough; no extra features are needed for this guide.
+
+The pattern itself has zero dependencies beyond what every Grails 8 starter already includes:
+
+* `spring-context` ships `ApplicationEventPublisher`, `@EventListener`, and `PayloadApplicationEvent`.
+* `spring-tx` ships `@TransactionalEventListener` and `TransactionPhase`.
+* `grails-datastore-gorm-hibernate` registers Spring's `HibernateTransactionManager` as the `PlatformTransactionManager` Spring uses to fire AFTER_COMMIT callbacks.
+
+Files touched in this chapter:
+
+* None
diff --git a/guides/grails-transactional-events/v8/guide/domainModel.adoc b/guides/grails-transactional-events/v8/guide/domainModel.adoc
new file mode 100644
index 00000000000..9b840c8c3ce
--- /dev/null
+++ b/guides/grails-transactional-events/v8/guide/domainModel.adoc
@@ -0,0 +1,32 @@
+Three domains model the example. `Customer` carries a denormalised `lifetimeValue`. `Order` belongs to a `Customer`. `AuditLog` is a flat append-only record of business events.
+
+[source,groovy]
+.grails-app/domain/example/Customer.groovy
+----
+include::../snippets/grails-app/domain/example/Customer.groovy[]
+----
+
+[source,groovy]
+.grails-app/domain/example/Order.groovy
+----
+include::../snippets/grails-app/domain/example/Order.groovy[]
+----
+
+[source,groovy]
+.grails-app/domain/example/AuditLog.groovy
+----
+include::../snippets/grails-app/domain/example/AuditLog.groovy[]
+----
+
+A few choices to point at:
+
+* `Customer.lifetimeValue` defaults to `BigDecimal.ZERO` and is constrained `min: BigDecimal.ZERO`. The `CustomerLifetimeValueListener` you'll write later is the only writer; the field never gets edited from `OrderService` or from a controller. That single-writer property is what makes the listener pattern composable - if any other listener wrote to the same field, you'd have a race.
+* `Order` declares `static mapping = { table 'orders' }` because `order` is a reserved word in most SQL dialects (it's the keyword in `ORDER BY`). Without the override the schema-generation either quotes the table name aggressively or fails outright depending on the database.
+* `AuditLog` deliberately does *not* use a foreign key to `Order` or `Customer`. It stores raw IDs and the snapshotted total. Audit history must survive the deletion of the rows it describes, and it must survive schema migrations that change the shape of `Order`.
+* Validation lives on the domains, not on the event class or the listeners. A listener receiving a malformed event is a programmer error; a listener receiving a well-formed event that fails domain validation is a domain change that needs a real migration.
+
+Files touched in this chapter:
+
+* `grails-app/domain/example/Customer.groovy`
+* `grails-app/domain/example/Order.groovy`
+* `grails-app/domain/example/AuditLog.groovy`
diff --git a/guides/grails-transactional-events/v8/guide/download.adoc b/guides/grails-transactional-events/v8/guide/download.adoc
new file mode 100644
index 00000000000..22d9b7fd8ec
--- /dev/null
+++ b/guides/grails-transactional-events/v8/guide/download.adoc
@@ -0,0 +1,14 @@
+Generate a Grails 8 starter from link:https://start.grails.org[start.grails.org]:
+
+[source,bash]
+----
+curl -sL "https://start.grails.org/grails/grails-transactional-events.zip?type=web&javaVersion=21&grailsVersion=8.0.0" -o grails-transactional-events.zip
+unzip grails-transactional-events.zip -d grails-transactional-events
+cd grails-transactional-events
+----
+
+You now have a Grails 8 / Spring Boot 4 / JDK 21 project ready to edit. The default `web` profile generates a GSP-rendered app; nothing else is required for the pattern.
+
+Files touched in this chapter:
+
+* None (project generation only)
diff --git a/guides/grails-transactional-events/v8/guide/eventClass.adoc b/guides/grails-transactional-events/v8/guide/eventClass.adoc
new file mode 100644
index 00000000000..6511b596241
--- /dev/null
+++ b/guides/grails-transactional-events/v8/guide/eventClass.adoc
@@ -0,0 +1,19 @@
+The event itself is a plain Groovy POGO. It carries the *minimum* data a listener needs to do its job - typically the IDs of the domain objects involved, plus any snapshotted value the listener should not look up again.
+
+[source,groovy]
+.src/main/groovy/example/events/OrderPlacedEvent.groovy
+----
+include::../snippets/src/main/groovy/example/events/OrderPlacedEvent.groovy[]
+----
+
+Three deliberate choices:
+
+* *No `extends ApplicationEvent`.* Since Spring Framework 4.2 (released 2015), `ApplicationEventPublisher` accepts any `Object`. If the published value isn't already an `ApplicationEvent`, Spring wraps it in a `PayloadApplicationEvent<T>` transparently. Listener methods declare the payload type as their parameter, never the wrapper. See link:https://docs.spring.io/spring-framework/docs/6.2.x/javadoc-api/org/springframework/context/PayloadApplicationEvent.html[`PayloadApplicationEvent` javadoc].
+* *`@Immutable`.* The event is data, not a state machine. Listeners may run on different threads (the `@Async` listener you'll write later runs on Spring's task executor), and the listener-execution order is unspecified - mutating the event from one listener to communicate with another is a contract violation waiting to happen. Groovy's `@Immutable` AST transformation generates a final-field, `equals`/`hashCode`-correct class for free.
+* *IDs, not references.* The event carries `customerId`, not a `Customer` instance. By the time the AFTER_COMMIT listeners run, the original Hibernate session is closed; passing a `Customer` instance would hand listeners a detached entity. Listeners that need the full row look it up by ID inside their own transaction.
+
+The event class lives under `src/main/groovy/example/events/` rather than `grails-app/services/` because it isn't a Grails artefact - Grails doesn't auto-register it as a Spring bean and there's nothing to inject. Plain Groovy under `src/main/groovy/` is the right home for it.
+
+Files touched in this chapter:
+
+* `src/main/groovy/example/events/OrderPlacedEvent.groovy`
diff --git a/guides/grails-transactional-events/v8/guide/gettingStarted.adoc b/guides/grails-transactional-events/v8/guide/gettingStarted.adoc
new file mode 100644
index 00000000000..1c344b72ffa
--- /dev/null
+++ b/guides/grails-transactional-events/v8/guide/gettingStarted.adoc
@@ -0,0 +1,5 @@
+In this guide you will solve a problem every non-trivial Grails app eventually meets: how to fan out business logic across several unrelated domains after a single domain object changes state, without tangling those side-effects into the originating service and without firing them when the originating transaction rolls back.
+
+The pattern - underused in Grails codebases - is Spring's `ApplicationEventPublisher` combined with `@TransactionalEventListener(phase = AFTER_COMMIT)`. Because GORM rides on Spring's `PlatformTransactionManager`, the integration is essentially free: publish a plain Groovy event from a `@Transactional` service, declare any number of listener beans, and Spring buffers the events until the database commit lands. Roll back, and the listeners are silently skipped.
+
+This guide targets Apache Grails 8 / Spring Boot 4 / JDK 21.
diff --git a/guides/grails-transactional-events/v8/guide/helpWithGrails.adoc b/guides/grails-transactional-events/v8/guide/helpWithGrails.adoc
new file mode 100644
index 00000000000..e062f614b1a
--- /dev/null
+++ b/guides/grails-transactional-events/v8/guide/helpWithGrails.adoc
@@ -0,0 +1 @@
+include::{commondir}/common-helpWithGrails.adoc[]
diff --git a/guides/grails-transactional-events/v8/guide/howto.adoc b/guides/grails-transactional-events/v8/guide/howto.adoc
new file mode 100644
index 00000000000..87fb7d0e7de
--- /dev/null
+++ b/guides/grails-transactional-events/v8/guide/howto.adoc
@@ -0,0 +1,10 @@
+You can either type the code in this guide as you read or skip ahead and clone the finished sample:
+
+[source,bash]
+----
+git clone -b grails8 https://github.com/grails-guides/grails-transactional-events.git
+cd grails-transactional-events/complete
+./gradlew integrationTest
+----
+
+`initial/` is the vanilla Grails 8 starter from link:https://start.grails.org[start.grails.org] with the default H2 in-memory database. `complete/` adds the `Customer`/`Order`/`AuditLog` domain model, the `OrderPlacedEvent` POGO, the `OrderService` publisher, the three listener beans, and the integration specs.
diff --git a/guides/grails-transactional-events/v8/guide/integrationTest.adoc b/guides/grails-transactional-events/v8/guide/integrationTest.adoc
new file mode 100644
index 00000000000..454d84cbf3c
--- /dev/null
+++ b/guides/grails-transactional-events/v8/guide/integrationTest.adoc
@@ -0,0 +1,27 @@
+The whole point of `AFTER_COMMIT` is that listeners do not fire when the publisher's transaction rolls back. That property is invisible in unit tests - it only shows up when a real Spring `PlatformTransactionManager` actually commits or rolls back a real database transaction. The right test layer is a Grails `@Integration` Spock spec.
+
+[source,groovy]
+.src/integration-test/groovy/example/OrderServiceIntegrationSpec.groovy
+----
+include::../snippets/src/integration-test/groovy/example/OrderServiceIntegrationSpec.groovy[]
+----
+
+A few details that catch people the first time:
+
+* *Why the spec is not annotated `@Rollback`.* The default integration-test behaviour in Grails wraps each test method in a transaction that's rolled back after the method returns. If you let that wrapper roll back the *outer* transaction, the AFTER_COMMIT listeners inside `placeOrder(...)` never fire - and the test cannot distinguish "the listener didn't run because of rollback semantics (good)" from "the listener didn't run because the test wrapper rolled back (irrelevant)". The spec t [...]
+* *Why `setRollbackOnly()` instead of throwing.* Throwing an exception from inside `withNewTransaction { ... }` would propagate out of the test method and fail the spec. `status.setRollbackOnly()` tells Spring to roll back when the block exits normally, which is exactly the "user-initiated rollback" scenario the test wants to model.
+* *Why the `cleanup:` block uses `withNewTransaction` again.* The test ran outside the integration-test transaction wrapper, so there is no automatic rollback to lean on. The cleanup must explicitly delete the rows the test created, in their own transaction, in the right order (`AuditLog` rows first because they reference `orderId`, then `Order`, then `Customer`).
+* *Why the async `NotificationListener` is not asserted on.* It logs only - there is nothing in the database to assert against. Testing that an `@Async` listener actually ran requires either an `awaitility`-style poll or replacing the executor with a synchronous one in the test profile. The two non-async listeners are sufficient to demonstrate the AFTER_COMMIT contract.
+
+Run the spec:
+
+[source,bash]
+----
+./gradlew integrationTest --tests example.OrderServiceIntegrationSpec
+----
+
+Both methods should pass. The first proves that AFTER_COMMIT listeners fire when the publisher commits; the second proves they're silently skipped when it rolls back. That's the entire contract the pattern guarantees.
+
+Files touched in this chapter:
+
+* `src/integration-test/groovy/example/OrderServiceIntegrationSpec.groovy`
diff --git a/guides/grails-transactional-events/v8/guide/multipleListeners.adoc b/guides/grails-transactional-events/v8/guide/multipleListeners.adoc
new file mode 100644
index 00000000000..937d67b7794
--- /dev/null
+++ b/guides/grails-transactional-events/v8/guide/multipleListeners.adoc
@@ -0,0 +1,21 @@
+The whole point of the pattern is that fanning out is cheap: a new side-effect is a new class, not an edit to `OrderService`. Here's a second listener that writes an `AuditLog` row.
+
+[source,groovy]
+.grails-app/services/example/AuditListener.groovy
+----
+include::../snippets/grails-app/services/example/AuditListener.groovy[]
+----
+
+Notice that this file is independent of `CustomerLifetimeValueListener`. They share nothing - no inheritance, no interface, no registry edit. Spring discovered both at startup, registered both against the `OrderPlacedEvent` type, and will call both (in unspecified order) when an order commits. Adding a third side-effect tomorrow - a webhook, a search-index refresh, a metrics counter - means writing a `WebhookListener` class. No other file changes.
+
+`AuditLog` snapshots the data it needs at event-time: `orderTotal` is copied from the event, not looked up by querying the (now-detached) `Order`. That decoupling has a few benefits:
+
+* The listener doesn't need a `Order.get(...)` round-trip. One INSERT per audit row.
+* The audit history is immune to later edits of `Order.total` (which shouldn't happen, but might).
+* If `Order` is hard-deleted later, the audit row still tells the full story.
+
+A common temptation is to add a `@Order(0)` annotation here to guarantee the audit row is written before the customer lifetime value updates. Resist it unless ordering is part of the actual business contract. Two AFTER_COMMIT listeners that need a specific ordering are usually one chained business operation in disguise, and the right refactor is to make the audit listener publish a second event the lifetime listener listens for - or to merge them into a single listener that does both wri [...]
+
+Files touched in this chapter:
+
+* `grails-app/services/example/AuditListener.groovy`
diff --git a/guides/grails-transactional-events/v8/guide/publishingEvents.adoc b/guides/grails-transactional-events/v8/guide/publishingEvents.adoc
new file mode 100644
index 00000000000..307590660ce
--- /dev/null
+++ b/guides/grails-transactional-events/v8/guide/publishingEvents.adoc
@@ -0,0 +1,19 @@
+The publisher side is the boring side. `OrderService.placeOrder(...)` is just a regular `@Transactional` Grails service that injects `ApplicationEventPublisher` and calls `publishEvent` once the persistence work is done.
+
+[source,groovy]
+.grails-app/services/example/OrderService.groovy
+----
+include::../snippets/grails-app/services/example/OrderService.groovy[]
+----
+
+What's notable is what's *not* in this class:
+
+* No `Set<EventListener>` field, no `EventBus` injection, no `for (listener : listeners) listener.fire(...)` loop. The publisher doesn't know who listens, how many listen, or whether anyone listens at all. Adding a fifth listener doesn't touch this file.
+* No `try/catch` around `publishEvent`. A failure in a listener is a listener bug; it must not unwind the originating order placement. (For AFTER_COMMIT listeners the order has already durably committed by the time the listener runs - rolling back the listener is mostly meaningless anyway.)
+* No transaction management beyond `@Transactional`. The method runs in a single GORM transaction. The `publishEvent` call hands the event to Spring's transaction synchronization manager; the listeners fire later, *after* this method's transaction commits.
+
+`ApplicationEventPublisher` is auto-injected because `ApplicationContext` implements it - every Spring application has exactly one publisher, available as a bean. `@Autowired` is explicit here but in Groovy services `def applicationEventPublisher` works too; the explicit declaration documents the type for readers.
+
+Files touched in this chapter:
+
+* `grails-app/services/example/OrderService.groovy`
diff --git a/guides/grails-transactional-events/v8/guide/requirements.adoc b/guides/grails-transactional-events/v8/guide/requirements.adoc
new file mode 100644
index 00000000000..734060b1bac
--- /dev/null
+++ b/guides/grails-transactional-events/v8/guide/requirements.adoc
@@ -0,0 +1,5 @@
+To complete this guide you will need:
+
+* JDK 21
+* About 30 minutes
+* An IDE that understands Groovy (IntelliJ IDEA recommended)
diff --git a/guides/grails-transactional-events/v8/guide/theProblem.adoc b/guides/grails-transactional-events/v8/guide/theProblem.adoc
new file mode 100644
index 00000000000..473c4415ceb
--- /dev/null
+++ b/guides/grails-transactional-events/v8/guide/theProblem.adoc
@@ -0,0 +1,21 @@
+Picture a checkout flow. `OrderService.placeOrder(...)` persists an `Order`. Three other things need to happen "right after" - but only if the order actually commits:
+
+* The `Customer.lifetimeValue` field on the buyer needs to be incremented.
+* An `AuditLog` row needs to be written for compliance.
+* A confirmation email needs to go out.
+
+The three obvious-but-wrong solutions:
+
+*Stuff every side-effect into `OrderService.placeOrder()`.* The service now reaches into `Customer`, into `AuditLog`, into the email subsystem. Add a fourth side-effect later (a search-index update, a Slack webhook, a usage-counter increment) and you keep editing the same method. Every concern in the system gets a line in `placeOrder`. The "place an order" intent disappears under the maintenance work.
+
+*Use a GORM domain-class callback like `Order.afterInsert`.* Closer, but two issues. The callback fires inside the Hibernate flush, not after the database commit. If the surrounding transaction rolls back later, the side-effects in `afterInsert` roll back too only if they used the same GORM session. Anything that touched an external system - the email send, the webhook - is already gone. Worse, GORM lifecycle callbacks live on the domain class itself, which has no Spring context, so call [...]
+
+*Use a plain Spring `ApplicationEvent` (without the transactional flavour).* This fires the listeners immediately when `publishEvent(...)` is called - which happens *inside* `OrderService.placeOrder()`, before its surrounding transaction has committed. A rollback after `publishEvent` leaves phantom audit rows, phantom emails, and (depending on isolation level) listeners that read the to-be-rolled-back order from the database and act on data that will not durably exist.
+
+The pattern this guide teaches is `@TransactionalEventListener(phase = TransactionPhase.AFTER_COMMIT)`. The publisher calls `publishEvent(...)` unconditionally. Spring buffers the event in the transaction synchronization manager and dispatches it to listener beans *only* after the database commit succeeds. Roll back, and the listeners never see the event. Each side-effect lives in its own class. Adding a fifth side-effect means writing a fifth class, not editing `OrderService`.
+
+Because GORM is implemented on top of Spring's `PlatformTransactionManager`, the wiring is the wiring you already have - no plugins, no GORM events bus, no `@EnableJpa*` annotations. Spring sees the commit on the GORM session, fires the synchronisation callback, and dispatches the event.
+
+Files touched in this chapter:
+
+* None
diff --git a/guides/grails-transactional-events/v8/guide/transactionPhases.adoc b/guides/grails-transactional-events/v8/guide/transactionPhases.adoc
new file mode 100644
index 00000000000..12b005fbc95
--- /dev/null
+++ b/guides/grails-transactional-events/v8/guide/transactionPhases.adoc
@@ -0,0 +1,39 @@
+`TransactionPhase` has four values. Pick the one that matches the side-effect's tolerance for the originating transaction being undone.
+
+[cols="1,2,3", options="header"]
+|===
+| Phase | Fires | Use for
+
+| `BEFORE_COMMIT`
+| Just before the database commit is issued, while the transaction is still open.
+| Side-effects that must be part of the same database commit as the originating change - typically derived data flushed into the same transaction. If the listener throws, the transaction rolls back.
+
+| `AFTER_COMMIT` (default)
+| After the database commit succeeds. The originating change is durable.
+| The 90% case: audit log writes, denormalised-field updates in other aggregates, outbound notifications, search-index refreshes, cache invalidations. Listener failures cannot undo the originating change - they must log and recover.
+
+| `AFTER_ROLLBACK`
+| After the database rollback completes. The originating change has been discarded.
+| Compensating side-effects: alerting on failed orders, releasing reserved inventory, decrementing speculative counters.
+
+| `AFTER_COMPLETION`
+| After the transaction completes, regardless of outcome. Aggregates both `AFTER_COMMIT` and `AFTER_ROLLBACK`.
+| Resource cleanup that must happen either way: closing a temporary file, releasing a distributed lock. Almost never the right choice for business logic, because the listener cannot easily tell which outcome occurred.
+|===
+
+A few rules that catch everyone the first time:
+
+* *No active transaction means no listener fires.* If `publishEvent(...)` is called outside a transactional context, the event is discarded. Override with `fallbackExecution = true` on the annotation if you really need the listener to run in the non-transactional case - but in a Grails service, `@Transactional` is almost always present and the fallback is rarely needed.
+* *`BEFORE_COMMIT` listeners run inside the publisher's transaction.* Anything the listener does to GORM is part of the same database commit. This is occasionally exactly what you want (e.g. derived totals) but it's a sharp edge - a listener exception unwinds the originating service call.
+* *`AFTER_COMMIT` listeners run *after* the publisher's transaction commits.* The publisher's GORM session is closed by the time the listener fires. The listener must open its own transaction (`REQUIRES_NEW`) to do any database work.
+* *Listener execution order is unspecified.* Spring does not guarantee the order in which two `AFTER_COMMIT` listeners for the same event fire. If you need ordering, use `@Order(...)` on the listener methods, but better: design the listeners so the order does not matter.
+
+References:
+
+* link:https://docs.spring.io/spring-framework/reference/data-access/transaction/event.html[Spring Framework Reference - Transaction-bound events]
+* link:https://docs.spring.io/spring-framework/docs/6.2.x/javadoc-api/org/springframework/transaction/event/TransactionalEventListener.html[`@TransactionalEventListener` javadoc]
+* link:https://docs.spring.io/spring-framework/docs/6.2.x/javadoc-api/org/springframework/transaction/event/TransactionPhase.html[`TransactionPhase` javadoc]
+
+Files touched in this chapter:
+
+* None
diff --git a/guides/grails-transactional-events/v8/guide/transactionalListener.adoc b/guides/grails-transactional-events/v8/guide/transactionalListener.adoc
new file mode 100644
index 00000000000..181f26aaaee
--- /dev/null
+++ b/guides/grails-transactional-events/v8/guide/transactionalListener.adoc
@@ -0,0 +1,21 @@
+The first listener bumps `Customer.lifetimeValue` after an order commits.
+
+[source,groovy]
+.grails-app/services/example/CustomerLifetimeValueListener.groovy
+----
+include::../snippets/grails-app/services/example/CustomerLifetimeValueListener.groovy[]
+----
+
+Walk through it:
+
+* The class lives in `grails-app/services/`, so Grails auto-registers it as a Spring bean named `customerLifetimeValueListener`. Spring's `EventListenerMethodProcessor` scans every bean's methods at startup for `@EventListener` / `@TransactionalEventListener` annotations and wires the listener registry from what it finds. There is no extra configuration step.
+* `@TransactionalEventListener(phase = TransactionPhase.AFTER_COMMIT)` binds the listener to the *publisher's* transaction synchronization. When `OrderService.placeOrder(...)` commits, Spring's `TransactionSynchronizationManager` fires the `afterCommit()` callback that drains the buffered events into this method. If `placeOrder(...)` rolls back, the buffered event is discarded and the method below is never called.
+* `@Transactional(propagation = REQUIRES_NEW)` opens a *new* transaction for the listener body. The publisher's transaction has already committed and its `Session` is closed by the time we get here - this method has no inherited GORM session. `REQUIRES_NEW` opens a fresh one and binds it to the calling thread for the duration of the listener.
+* The method parameter type `OrderPlacedEvent` is how Spring picks which listener to call for which event. A second listener that accepts `CustomerRegisteredEvent` won't see `OrderPlacedEvent`s, and vice versa. The event-to-listener wiring is implicit in the parameter type.
+* The `if (customer)` guard handles the (degenerate) case where the customer row has been deleted between the publisher commit and the listener firing. In a single-node deployment this is essentially impossible; in a multi-node deployment with concurrent admin tooling it can happen and the listener should noop rather than throw.
+
+One thing the listener deliberately doesn't do: re-publish another event. AFTER_COMMIT listeners can call `applicationEventPublisher.publishEvent(...)` themselves, but doing so creates an event chain that lives outside the original publisher's transaction. Keep listener responsibilities narrow; if a second event is logically part of the same business operation, publish it from the original service.
+
+Files touched in this chapter:
+
+* `grails-app/services/example/CustomerLifetimeValueListener.groovy`
diff --git a/guides/grails-transactional-events/v8/guide/vsGormEvents.adoc b/guides/grails-transactional-events/v8/guide/vsGormEvents.adoc
new file mode 100644
index 00000000000..3421d048b49
--- /dev/null
+++ b/guides/grails-transactional-events/v8/guide/vsGormEvents.adoc
@@ -0,0 +1,41 @@
+Grails has *three* mechanisms that loosely resemble "do something when a domain object changes". They look interchangeable in tutorials and are not interchangeable in practice. Here's the contrast that the rest of this guide implicitly assumes.
+
+[cols="1,3,3,2", options="header"]
+|===
+| Mechanism | Fires when | Lives where | Use for
+
+| Domain-class lifecycle callbacks +
+(`beforeInsert`, `afterInsert`, `beforeUpdate`, `afterUpdate`, `beforeDelete`, `afterDelete`)
+| During the Hibernate flush, *inside* the surrounding transaction. Bound to a specific domain class.
+| As methods on the domain class itself. The domain class is not a Spring bean; injecting other Spring beans is awkward (use `Holders.applicationContext.getBean(...)` or the deprecated `defineBeans` indirection).
+| Trivial single-domain hygiene that *must* be in the same database transaction. Setting a `createdBy` field, normalising a string, computing a derived column. Never for cross-domain or external-system work.
+
+| Grails events (`@Listener`, `@Subscriber`, `EventBus`)
+| At Hibernate-event level, synchronously (`@Listener`) or via the EventBus (`@Subscriber`). Still bound to the persistence flush, not to the Spring transaction commit.
+| Beans annotated with the Grails-specific annotations. Publisher uses `EventPublisher` or the `eventBus` bean.
+| Grails-internal events you didn't define (think GORM-level audit, soft-delete plugin hooks). The vocabulary is GORM-flavoured: `PreInsertEvent`, `PostUpdateEvent`, `PreDeleteEvent`.
+
+| Spring application events +
+(`ApplicationEventPublisher`, `@EventListener`, *`@TransactionalEventListener`*)
+| `@EventListener` - the moment `publishEvent` is called. +
+`@TransactionalEventListener` - bound to the *Spring transaction* commit/rollback, not the Hibernate flush.
+| Any Spring bean. Publisher is `ApplicationEventPublisher`, available everywhere.
+| Cross-domain business logic, especially anything that touches an external system (email, search index, webhook, cache) and must only run on durable commit. *This guide's pattern.*
+|===
+
+Three rules that come out of the table:
+
+* If the side-effect is single-domain and *must* be in the same transaction (a derived column, a `createdBy` audit field), use a lifecycle callback. Don't reach for an event system.
+* If the side-effect crosses domains *and* should only happen on durable commit (an audit row, an email, a webhook), use `@TransactionalEventListener(AFTER_COMMIT)`. This is the gap GORM lifecycle callbacks don't fill.
+* If you're reading existing code that uses `@Subscriber` / `@Listener` for cross-domain business logic, treat it as a smell. Those annotations were originally designed for Grails plugin developers extending GORM, not for application-level cross-domain logic. The Spring-transactional pattern in this guide is the cleaner replacement.
+
+A common claim worth being precise about: "transactional Spring events just work with GORM." That's true, and the reason is mechanical, not magical. GORM ships `HibernateTransactionManager` as the Spring `PlatformTransactionManager` bean. `@TransactionalEventListener` registers a transaction-synchronization callback on the *current* `PlatformTransactionManager`. Since that's the same `HibernateTransactionManager` GORM is committing through, the AFTER_COMMIT callback fires exactly when th [...]
+
+References:
+
+* link:https://grails.apache.org/guides/gorm-event-listeners/4/guide/index.html[grails-guides/gorm-event-listeners - the official walk-through of the GORM lifecycle approach]
+* link:https://grails.apache.org/docs/snapshot/guide/async.html#_events_from_spring[Grails Async Guide - "Events from Spring"] - covers the legacy Grails EventBus bridge to Spring events, off by default.
+
+Files touched in this chapter:
+
+* None
diff --git a/guides/grails-transactional-events/v8/guide/whatYouWillBuild.adoc b/guides/grails-transactional-events/v8/guide/whatYouWillBuild.adoc
new file mode 100644
index 00000000000..3d94d67e840
--- /dev/null
+++ b/guides/grails-transactional-events/v8/guide/whatYouWillBuild.adoc
@@ -0,0 +1,12 @@
+By the end of the guide you will have:
+
+* A three-domain model - `Customer`, `Order`, and `AuditLog` - with `Order belongsTo: Customer` and a denormalised `Customer.lifetimeValue` field that downstream listeners maintain.
+* An immutable POGO event class `OrderPlacedEvent` under `src/main/groovy/example/events/`. No `ApplicationEvent` inheritance: Spring 4.2+ accepts any object as a published event.
+* An `OrderService.placeOrder(...)` method annotated `@Transactional` that persists an `Order` and publishes an `OrderPlacedEvent` via an injected `ApplicationEventPublisher`.
+* Three independent listener services:
+** `CustomerLifetimeValueListener` - bumps `Customer.lifetimeValue` after commit.
+** `AuditListener` - writes an `AuditLog` row after commit.
+** `NotificationListener` - dispatched off-thread via `@Async` after commit (a stand-in for sending email).
+* Two Spock integration specs that prove the non-negotiable contract: AFTER_COMMIT listeners fire when (and only when) the publisher's transaction commits, and are silently skipped when it rolls back.
+* A reference table of all four `TransactionPhase` values - `BEFORE_COMMIT`, `AFTER_COMMIT`, `AFTER_ROLLBACK`, `AFTER_COMPLETION` - explaining what each one is good for.
+* A side-by-side contrast with GORM's domain-class lifecycle callbacks (`beforeInsert` / `afterInsert`) and Grails' `@Subscriber` / `@Listener` annotations, so you know which mechanism to reach for and when.
diff --git a/guides/grails-transactional-events/v8/snippets/grails-app/domain/example/AuditLog.groovy b/guides/grails-transactional-events/v8/snippets/grails-app/domain/example/AuditLog.groovy
new file mode 100644
index 00000000000..f3addf36c8b
--- /dev/null
+++ b/guides/grails-transactional-events/v8/snippets/grails-app/domain/example/AuditLog.groovy
@@ -0,0 +1,25 @@
+package example
+
+import grails.persistence.Entity
+
+@Entity
+class AuditLog {
+
+    String eventType
+    Long orderId
+    Long customerId
+    BigDecimal orderTotal
+    Date occurredAt
+
+    static constraints = {
+        eventType  blank: false, maxSize: 64
+        orderId    min: 1L
+        customerId min: 1L
+        orderTotal min: new BigDecimal('0.01')
+        occurredAt nullable: false
+    }
+
+    static mapping = {
+        orderTotal scale: 2, precision: 19
+    }
+}
diff --git a/guides/grails-transactional-events/v8/snippets/grails-app/domain/example/Customer.groovy b/guides/grails-transactional-events/v8/snippets/grails-app/domain/example/Customer.groovy
new file mode 100644
index 00000000000..445ea78efd0
--- /dev/null
+++ b/guides/grails-transactional-events/v8/snippets/grails-app/domain/example/Customer.groovy
@@ -0,0 +1,23 @@
+package example
+
+import grails.persistence.Entity
+
+@Entity
+class Customer {
+
+    String name
+    String email
+    BigDecimal lifetimeValue = BigDecimal.ZERO
+
+    static constraints = {
+        name          blank: false, maxSize: 255
+        email         email: true, unique: true, maxSize: 255
+        lifetimeValue min: BigDecimal.ZERO
+    }
+
+    static mapping = {
+        lifetimeValue scale: 2, precision: 19
+    }
+
+    String toString() { name }
+}
diff --git a/guides/grails-transactional-events/v8/snippets/grails-app/domain/example/Order.groovy b/guides/grails-transactional-events/v8/snippets/grails-app/domain/example/Order.groovy
new file mode 100644
index 00000000000..4bad44b946d
--- /dev/null
+++ b/guides/grails-transactional-events/v8/snippets/grails-app/domain/example/Order.groovy
@@ -0,0 +1,23 @@
+package example
+
+import grails.persistence.Entity
+
+@Entity
+class Order {
+
+    Customer customer
+    BigDecimal total
+    Date dateCreated
+
+    static belongsTo = [customer: Customer]
+
+    static constraints = {
+        total min: new BigDecimal('0.01')
+    }
+
+    static mapping = {
+        // 'order' is reserved in most SQL dialects
+        table 'orders'
+        total scale: 2, precision: 19
+    }
+}
diff --git a/guides/grails-transactional-events/v8/snippets/grails-app/init/example/BootStrap.groovy b/guides/grails-transactional-events/v8/snippets/grails-app/init/example/BootStrap.groovy
new file mode 100644
index 00000000000..2117594aa00
--- /dev/null
+++ b/guides/grails-transactional-events/v8/snippets/grails-app/init/example/BootStrap.groovy
@@ -0,0 +1,13 @@
+package example
+
+class BootStrap {
+
+    def init = { servletContext ->
+        if (Customer.count() == 0) {
+            new Customer(name: 'Alice Wong', email: 'alice@example.com').save(failOnError: true)
+            new Customer(name: 'Bob Chen',   email: 'bob@example.com').save(failOnError: true)
+        }
+    }
+
+    def destroy = { }
+}
diff --git a/guides/grails-transactional-events/v8/snippets/grails-app/services/example/AuditListener.groovy b/guides/grails-transactional-events/v8/snippets/grails-app/services/example/AuditListener.groovy
new file mode 100644
index 00000000000..3fa58fe37d4
--- /dev/null
+++ b/guides/grails-transactional-events/v8/snippets/grails-app/services/example/AuditListener.groovy
@@ -0,0 +1,30 @@
+package example
+
+import example.events.OrderPlacedEvent
+import grails.gorm.transactions.Transactional
+import org.springframework.transaction.annotation.Propagation
+import org.springframework.transaction.event.TransactionPhase
+import org.springframework.transaction.event.TransactionalEventListener
+
+/**
+ * Persists an AuditLog row for every committed order.
+ *
+ * A separate listener class - not a method on OrderService - keeps the
+ * "place an order" concern decoupled from the "record audit history"
+ * concern. Adding another committed-only side-effect later means a new
+ * class, not an edit to OrderService.
+ */
+class AuditListener {
+
+    @TransactionalEventListener(phase = TransactionPhase.AFTER_COMMIT)
+    @Transactional(propagation = Propagation.REQUIRES_NEW)
+    void onOrderPlaced(OrderPlacedEvent event) {
+        new AuditLog(
+                eventType:  'ORDER_PLACED',
+                orderId:    event.orderId,
+                customerId: event.customerId,
+                orderTotal: event.total,
+                occurredAt: new Date()
+        ).save(failOnError: true)
+    }
+}
diff --git a/guides/grails-transactional-events/v8/snippets/grails-app/services/example/CustomerLifetimeValueListener.groovy b/guides/grails-transactional-events/v8/snippets/grails-app/services/example/CustomerLifetimeValueListener.groovy
new file mode 100644
index 00000000000..aefb4f15cce
--- /dev/null
+++ b/guides/grails-transactional-events/v8/snippets/grails-app/services/example/CustomerLifetimeValueListener.groovy
@@ -0,0 +1,27 @@
+package example
+
+import example.events.OrderPlacedEvent
+import grails.gorm.transactions.Transactional
+import org.springframework.transaction.annotation.Propagation
+import org.springframework.transaction.event.TransactionPhase
+import org.springframework.transaction.event.TransactionalEventListener
+
+/**
+ * Updates Customer.lifetimeValue when an order commits.
+ *
+ * Grails auto-registers everything in grails-app/services/ as a Spring bean,
+ * so @TransactionalEventListener annotations on methods here are picked up
+ * by Spring's EventListenerMethodProcessor at startup.
+ */
+class CustomerLifetimeValueListener {
+
+    @TransactionalEventListener(phase = TransactionPhase.AFTER_COMMIT)
+    @Transactional(propagation = Propagation.REQUIRES_NEW)
+    void onOrderPlaced(OrderPlacedEvent event) {
+        Customer customer = Customer.get(event.customerId)
+        if (customer) {
+            customer.lifetimeValue = (customer.lifetimeValue ?: BigDecimal.ZERO) + event.total
+            customer.save(flush: true, failOnError: true)
+        }
+    }
+}
diff --git a/guides/grails-transactional-events/v8/snippets/grails-app/services/example/NotificationListener.groovy b/guides/grails-transactional-events/v8/snippets/grails-app/services/example/NotificationListener.groovy
new file mode 100644
index 00000000000..da2851bfc3d
--- /dev/null
+++ b/guides/grails-transactional-events/v8/snippets/grails-app/services/example/NotificationListener.groovy
@@ -0,0 +1,37 @@
+package example
+
+import example.events.OrderPlacedEvent
+import org.slf4j.Logger
+import org.slf4j.LoggerFactory
+import org.springframework.scheduling.annotation.Async
+import org.springframework.transaction.event.TransactionPhase
+import org.springframework.transaction.event.TransactionalEventListener
+
+/**
+ * Off-thread side-effect: stand-in for sending a confirmation email.
+ *
+ * @Async dispatches the listener body to Spring's task executor instead
+ * of running it on the caller's thread. The transaction-phase binding
+ * is still synchronous - Spring waits for AFTER_COMMIT, then hands the
+ * event to the executor. The listener body therefore has NO inherited
+ * transaction; if it needs the database it must open its own via
+ * @Transactional(propagation = REQUIRES_NEW).
+ *
+ * Exceptions thrown from an @Async listener are NOT propagated to the
+ * publisher - see Spring's AsyncUncaughtExceptionHandler.
+ *
+ * @EnableAsync must be present on Application.groovy for @Async to take
+ * effect; without it the annotation is silently a no-op.
+ */
+class NotificationListener {
+
+    private static final Logger log = LoggerFactory.getLogger(NotificationListener)
+
+    @Async
+    @TransactionalEventListener(phase = TransactionPhase.AFTER_COMMIT)
+    void onOrderPlaced(OrderPlacedEvent event) {
+        log.info('Off-thread: sending confirmation email for order {} (total {})',
+                event.orderId, event.total)
+        // Real implementation would call emailService.send(...)
+    }
+}
diff --git a/guides/grails-transactional-events/v8/snippets/grails-app/services/example/OrderService.groovy b/guides/grails-transactional-events/v8/snippets/grails-app/services/example/OrderService.groovy
new file mode 100644
index 00000000000..e8916c3c164
--- /dev/null
+++ b/guides/grails-transactional-events/v8/snippets/grails-app/services/example/OrderService.groovy
@@ -0,0 +1,31 @@
+package example
+
+import example.events.OrderPlacedEvent
+import grails.gorm.transactions.Transactional
+import org.springframework.beans.factory.annotation.Autowired
+import org.springframework.context.ApplicationEventPublisher
+
+@Transactional
+class OrderService {
+
+    @Autowired
+    ApplicationEventPublisher applicationEventPublisher
+
+    Order placeOrder(Long customerId, BigDecimal total) {
+        Customer customer = Customer.get(customerId)
+        if (!customer) {
+            throw new IllegalArgumentException("Unknown customer: ${customerId}")
+        }
+
+        Order order = new Order(customer: customer, total: total).save(failOnError: true)
+
+        // Fire-and-forget from the publisher's point of view. Spring buffers
+        // the event in the synchronization manager and dispatches it to
+        // @TransactionalEventListener beans only after this method's
+        // transaction commits.
+        applicationEventPublisher.publishEvent(
+                new OrderPlacedEvent(order.id, customer.id, total))
+
+        order
+    }
+}
diff --git a/guides/grails-transactional-events/v8/snippets/src/integration-test/groovy/example/OrderServiceIntegrationSpec.groovy b/guides/grails-transactional-events/v8/snippets/src/integration-test/groovy/example/OrderServiceIntegrationSpec.groovy
new file mode 100644
index 00000000000..c1a24ea75ef
--- /dev/null
+++ b/guides/grails-transactional-events/v8/snippets/src/integration-test/groovy/example/OrderServiceIntegrationSpec.groovy
@@ -0,0 +1,83 @@
+package example
+
+import grails.testing.mixin.integration.Integration
+import spock.lang.Specification
+
+/**
+ * Integration spec that proves the two non-negotiable claims:
+ *
+ *   1. AFTER_COMMIT listeners fire when (and only when) the outer
+ *      transaction commits.
+ *   2. AFTER_COMMIT listeners are silently skipped when the outer
+ *      transaction rolls back - no phantom audit rows, no phantom
+ *      emails for orders that never durably existed.
+ *
+ * Each test method opens its own committed transaction via
+ * Customer.withNewTransaction { ... } / Order.withNewTransaction { ... }
+ * because @Rollback would also prevent the AFTER_COMMIT listeners from
+ * firing, which would conflate "the listener never ran because rollback"
+ * with "the listener never ran because @Rollback".
+ */
+@Integration
+class OrderServiceIntegrationSpec extends Specification {
+
+    OrderService orderService
+
+    void "AFTER_COMMIT listeners run only after the outer transaction commits"() {
+        given:
+        Customer customer = createCommitted('Eve Lin', 'eve@example.com')
+        long auditBefore = AuditLog.count()
+        BigDecimal lvBefore = Customer.get(customer.id).lifetimeValue
+
+        when: 'placeOrder runs inside a transaction that commits'
+        Order placed = null
+        Order.withNewTransaction {
+            placed = orderService.placeOrder(customer.id, new BigDecimal('19.95'))
+        }
+
+        then: 'Both AFTER_COMMIT listeners fired'
+        AuditLog.count() == auditBefore + 1
+        Customer.get(customer.id).lifetimeValue == lvBefore + new BigDecimal('19.95')
+
+        cleanup:
+        deleteCommitted(placed, customer)
+    }
+
+    void "AFTER_COMMIT listeners are skipped when the outer transaction rolls back"() {
+        given:
+        Customer customer = createCommitted('Fay Park', 'fay@example.com')
+        long auditBefore = AuditLog.count()
+        BigDecimal lvBefore = Customer.get(customer.id).lifetimeValue
+
+        when: 'placeOrder runs inside a transaction that explicitly rolls back'
+        Order.withNewTransaction { status ->
+            orderService.placeOrder(customer.id, new BigDecimal('999.00'))
+            status.setRollbackOnly()
+        }
+
+        then: 'Neither AFTER_COMMIT listener fired'
+        AuditLog.count() == auditBefore
+        Customer.get(customer.id).lifetimeValue == lvBefore
+
+        cleanup:
+        deleteCommitted(null, customer)
+    }
+
+    private Customer createCommitted(String name, String email) {
+        Customer created = null
+        Customer.withNewTransaction {
+            created = new Customer(name: name, email: email).save(flush: true, failOnError: true)
+        }
+        created
+    }
+
+    private void deleteCommitted(Order placed, Customer customer) {
+        Order.withNewTransaction {
+            if (placed) {
+                AuditLog.where { orderId == placed.id }.deleteAll()
+                Order.get(placed.id)?.delete(flush: true)
+            }
+            Customer.get(customer.id)?.delete(flush: true)
+        }
+    }
+}
diff --git a/guides/grails-transactional-events/v8/snippets/src/main/groovy/example/events/OrderPlacedEvent.groovy b/guides/grails-transactional-events/v8/snippets/src/main/groovy/example/events/OrderPlacedEvent.groovy
new file mode 100644
index 00000000000..8863fd78c3f
--- /dev/null
+++ b/guides/grails-transactional-events/v8/snippets/src/main/groovy/example/events/OrderPlacedEvent.groovy
@@ -0,0 +1,18 @@
+package example.events
+
+import groovy.transform.Immutable
+
+/**
+ * Domain event published by OrderService after an Order is persisted.
+ *
+ * No ApplicationEvent inheritance is required. Spring's
+ * ApplicationEventPublisher.publishEvent(Object) overload wraps any
+ * payload in a PayloadApplicationEvent transparently, so plain POGOs
+ * are the recommended event type since Spring Framework 4.2.
+ */
+@Immutable
+class OrderPlacedEvent {
+    Long orderId
+    Long customerId
+    BigDecimal total
+}