title: Use Spring IoC to manage Hibernate Interceptor
body: <p>I'm using Spring Boot v2.0.3 with Hibernate 5.2. I would like to create an Hibernate Interceptor to generate a value in one of my entity field, based on a unique number in my database, before it got saved.</p>
  
  <p>I fetched some online ressources, and ended up extending the Hibernate EmptyInterceptor to just override the onSave method.</p>
  
  <pre><code>@Component
  public class CustomInterceptor extends EmptyInterceptor {
  
      private final TicketService ticketService;
  
      @Autowired
      public CustomInterceptor(TicketService ticketService) {
          this.ticketService = ticketService;
      }
  
      public boolean onSave(Object entity,
                         Serializable id,
                         Object[] state,
                         String[] propertyNames,
                         Type[] types) {
  
          if (entity instanceof Ticket) {
              if (((Ticket) entity).getNumTicket() == null) {
                  String pharmacyId = ((Ticket) entity).getEtablishmentId();
  
                  Long newTicketNumber = ticketService.findMaxNumTicketForEtablishment(etablishmentId);
                  // ((Ticket) entity).setNumTicket((newTicketNumber != null ? newTicketNumber : 1));
                  for ( int i = 0; i &lt; propertyNames.length; i++ ) {
                      if ( "numTicket".equals( propertyNames[i] ) ) {
                          state[i] = newTicketNumber;
                          return true;
                      }
                  }
                  return true;
              }
          }
          return false;
      }
  }
  </code></pre>
  
  <p>In my application.yml config file, I added the following key : </p>
  
  <pre><code>spring.jpa.properties.hibernate.ejb.interceptor: com.mycompany.xxx.utils.CustomInterceptor
  </code></pre>
  
  <p>When I try a Ticket saving, I can see that the method onSave is correctly called, but as the interceptor was instantiated purely by Hibernate, it's not in the Spring bean context, so I can't use the @Autowire annotation. (so my ticketService is null).</p>
  
  <p>In a old subject ( <a href="https://stackoverflow.com/questions/25283767/how-to-use-spring-managed-hibernate-interceptors-in-spring-boot/31725844">How to use Spring managed Hibernate interceptors in Spring Boot?</a>), I see that someone tried to override the HibernateJpaAutoConfiguration vendor properties, but it's not available anymore.</p>
  
  <p>I found this issue on Github : <a href="https://github.com/spring-projects/spring-boot/issues/11211" rel="nofollow noreferrer">https://github.com/spring-projects/spring-boot/issues/11211</a> , perfectly illustrating my problem, but I couldn't successfully make it work (tried to create an HibernatePropertieCustomizer as well, but I failed to use it).</p>
  
  <p>if anyone can point me out to the right direction, I would be grateful. thanks</p>