title: Why does my Spring @EventListener show different transactional behavior on event submission than when being called directly?
body: <p>When using the <code>@EventListener</code> functionality with Spring Data's repositories the behavior is different than when calling the same code procedural.</p>
  
  <p>My persistent objects publish events using the following base class:</p>
  
  <pre><code>  public abstract class Aggregate  {
  
        @Transient
        private transient final Set&lt;Object&gt; events = new LinkedHashSet&lt;&gt;();
  
        protected &lt;T&gt; T registerEvent(T event) {
            this.events.add(event);
            return event;
        }
  
        @DomainEvents
        Collection&lt;Object&gt; events() {
            return Collections.unmodifiableSet(events);
        }
  
        @AfterDomainEventPublication
        void clearEvents() {
            this.events.clear();
        }
    }
  </code></pre>
  
  <p>My event listening class is implemented as follows:</p>
  
  <pre><code>  class Service {
  
        @EventListener
        public void listener(SomeEvent event) {
            someOtherRepository.save(someOtherPersistentObject);
            someOtherCode();
        }
    }
  </code></pre>
  
  <p>When the listener is triggered and <code>someOtherRepository</code>'s <code>save(…)</code> method fails a rollback will be issued. But <code>someOtherCode()</code> is executed regardless of the rollback.</p>
  
  <p>But when I remove all <code>@EventListening</code> functionality and call the <code>listener(…)</code> method directly after the point where the originating repository is responsible for firing the event. Then I get a different behavior. Then <code>someOtherCode()</code> is never executed and the <code>someOtherRepository.save(…)</code> method fails immediately.</p>
  
  <p>The original service responsible for publishing the event looks like this</p>
  
  <pre><code>public OriginatingService {
      @Transactional
      public void someMethod() {
          originatingRepoDifferentFromSomeOtherRepo.save(something);
  </code></pre>
  
  <p>Why is this happening and is there a way to force the same behavior onto my event listening implementation?</p>