title: How to properly publish DDD domain events with spring?
body: <p>I am trying to implement domain driven design in my project.
  Here is my base <code>Aggregate</code> class:</p>
  
  <pre><code>public abstract class UUIDAggregate {
      private final DomainEventPublisher domainEventPublisher;
  
      protected void publish(DomainEvent domainEvent) {
          domainEventPublisher.publish(domainEvent);
      }
  }
  </code></pre>
  
  <p>Let's say we have <code>UserAccount</code> aggregate:</p>
  
  <pre><code>public class UserAccount extends UUIDAggregate {
      private String email;
      private String username;
      private String password;
      private String firstName;
      private String lastName;
  
      public void update() {
          publish(new DomainEventImpl());
      }
  }
  </code></pre>
  
  <p>Here is my <code>DomainEventPublisher</code>:</p>
  
  <pre><code>public interface DomainEventPublisher {
     void publish(DomainEvent event);
  }
  </code></pre>
  
  <p>Here is <code>DomainEventPublisherImpl</code>:</p>
  
  <pre><code>@Component
  public class DomainEventPublisherImpl implements DomainEventPublisher{
      @Autowired
      private ApplicationEventPublisher publisher;
  
      public void publish(DomainEvent event){
          publisher.publishEvent(event);
      }
  }
  </code></pre>
  
  <p>Now, this seems like a good idea, the domain is separated from implementation but this does not work. <code>DomainEventPublisher</code> cannot be <code>Autowired</code> because <code>UUIDAggregate</code> is not a <code>@Component</code> or <code>@Bean</code> . One solution would be to create <code>DomainService</code> and publish event there but that seems like leaking of domain to domain service and if I go that way, I am going to anemic model. Also what I can do is to pass <code>DomainEventPublisher</code> as a parameter to every aggregate but that also does not seems like a good idea.</p>