Uploaded image for project: 'Spring Data Commons'
  1. Spring Data Commons
  2. DATACMNS-928

Support for exposing domain events from aggregate roots as Spring application events

    Details

    • Sprint:
      Kay M1, Ingalls RC1

      Description

      Context

      One important element of Domain-Driven Design is exposing events important to the domain to other components. These events are produced by aggregates and usually are tied to state transitions of the aggregate. Right now, a typical pattern to produce those events is this:

      @RequiredArgsConstructor
      class MyComponent {
       
        private final @NonNull MyRepository repository;
        private final @NonNull ApplicationEventPublisher publisher;
       
        public void doSomething(MyAggregateRoot entity) {
       
          MyDomainEvent event = entity.someBusinessFunctionality();
          publisher.publishEvent(event);
          repository.save(entity);
        }
      }
      

      Problem

      As you can see, the client needs to use ApplicationEventPublisher explicitly. If we provided a way for the aggregate root to expose the events to be published, the repository could take over the burden to publish the events.

      Proposed solution

      First of all we need means to let the aggregate root expose the events to be published. This could be an annotation based approach like this:

      class MyAggregateRoot {
       
        @PublishedDomainEvents
        Collection<Object> domainEvents() {
        }
      }
      

      The annotation name to be open for discussion, of course. We could support to return a Collection of events or a single one. The same could be achieved with an interface, of course.

      The repository infrastructure could then inspect the aggregate root type for a method declaration with said annotation (or a type check for the interface pendant) and add an interceptor to the repository proxy that holds a reference to the ApplicationEventPublisher, grabs the events to publish from the aggregate and publishes them before forwarding the call.

        Activity

        Hide
        jblum John Blum added a comment -

        I quite like this Ollie; I think this is a nice/clean design and approach.

        Show
        jblum John Blum added a comment - I quite like this Ollie; I think this is a nice/clean design and approach.

          People

          • Assignee:
            olivergierke Oliver Gierke
            Reporter:
            olivergierke Oliver Gierke
            Last updater:
            Oliver Gierke
          • Votes:
            2 Vote for this issue
            Watchers:
            4 Start watching this issue

            Dates

            • Created:
              Updated:
              Resolved:

              Agile