title: How to register hibernate spring entity listeners
body: <p>I have built an entity listener but have not figured out how to register it so that it will get called.  This all runs, and I verified in the debugger that the 
  registration code executes (apparently successfully) at startup.  But the debugger never stops in the listener code.</p>
  
  <p>This is my listener:</p>
  
  <pre><code>public class DirtyAwareListener implements PostLoadEventListener
  {
     @Override
     public void onPostLoad(PostLoadEvent postLoadEvent)
     {
        if (postLoadEvent.getEntity() instanceof DirtyAware)
        {
           ((DirtyAware)postLoadEvent.getEntity()).commitFields();
        }
     }
  }
  </code></pre>
  
  <p>and this is the registration component:</p>
  
  <pre><code>@Component
  public class HibernateListenerConfigurer
  {
     @PersistenceUnit
     private EntityManagerFactory emf;
  
     @Autowired
     private SessionFactory sessionFactory;
  
     @PostConstruct
     protected void init()
     {
        DirtyAwareListener listener = new DirtyAwareListener();
  //      SessionFactoryImpl sessionFactory = emf.unwrap(SessionFactoryImpl.class);
        EventListenerRegistry registry = ((SessionFactoryImpl)sessionFactory).getServiceRegistry().getService(EventListenerRegistry.class);
        registry.getEventListenerGroup(EventType.POST_LOAD).appendListener(listener);
     }
  }
  </code></pre>
  
  <p>Here is how my general Hibernate configuration code generates a session factory:</p>
  
  <pre><code>    LocalSessionFactoryBean sessionFactory = new LocalSessionFactoryBean();
      sessionFactory.setDataSource(getDataSource());
      sessionFactory.setPackagesToScan("com.my.entities");
      sessionFactory.setHibernateProperties(getHibernateProperties());
      sessionFactory.setEntityInterceptor(new DirtyAwareInterceptor());
      return sessionFactory;
  </code></pre>
  
  <p>Note that the interceptor does work as expected (but unfortunately does not have hooks where I need them.)</p>