title: Can it register an domain event in the constructor of aggregate root, when using Spring Data Common
body: <p>The aggregate will be created by some <code>application service</code>, not by another aggregate.</p>
  
  <p>Like this</p>
  
  <pre><code>SomeAggregate aggregate = new SomeAggregate();
  repo.save(aggregate);
  </code></pre>
  
  <p>The expectation is that the <code>aggregate</code> is saved and one <code>SomeAggregateCreated</code> event is published when the application service is over. I have tested it, it is not always effective, sometimes the event is not registered immediately after the constructor is executed.</p>
  
  <p>This is the teacher class:</p>
  
  <pre><code>public class Teacher extends AbstractAggregateRoot&lt;Teacher&gt; {
  
      public Teacher() {
          registerEvent(new TeacherAdded(id, name));
      }
  }
  </code></pre>
  
  <p>This is the <code>TeacherAdded</code>:   </p>
  
  <pre><code>@AllArgsConstructor
  @Getter
  @ToString
  @EqualsAndHashCode(callSuper = true)
  public class TeacherAdded extends AbstractDomainEvent {
      private TeacherId teacherId;    
      private String name;
  }
  </code></pre>
  
  <p>This is <code>AbstractDomainEvent</code> and <code>DomainEvent</code></p>
  
  <pre><code>@Getter
  @ToString()
  @EqualsAndHashCode()
  public abstract class AbstractDomainEvent implements DomainEvent {
      protected Date occurredOn;
  
      public AbstractDomainEvent() {
          this(new Date());
      }
  
      public AbstractDomainEvent(Date occurredOn) {
          this.occurredOn = occurredOn != null ? occurredOn : new Date();
      }
  
      @Override
      public Date occurredOn() {
          return occurredOn;
      }    
  }
  
  public interface DomainEvent {
      public Date occurredOn();
  }
  </code></pre>
  
  <p>The <code>AbstractAggregateRoot</code> is copied from <code>org.springframework.data.domain.AbstractAggregateRoot&lt;A&gt;</code>, and the <code>hasCapturedEvent</code> method is added for testing.</p>
  
  <pre><code>public boolean hasCapturedEvent(DomainEvent event) {
      return domainEvents.contains(event);
  }
  </code></pre>
  
  <p>If I run this:</p>
  
  <pre><code>// ...
  TeacherAdded teacherAdded = new TeacherAdded(teacherId, teacherName);
  Teacher teacher = new Teacher();
  assertTrue(teacher.hasCapturedEvent(teacherAdded)); 
  </code></pre>
  
  <p>It sometimes fails and sometimes succeeds.</p>