Why doesn't HibernateTransactionManager use autowire Spring injection?

In Interceptor class for automatic auditing of Hibernate CRUD @ operations, Automatic annotation from Spring does not work.

I suppose this is due to the fact that during configuration Spring has not yet had time to set up autoincrement. Everything is going well in other classes. Is there a workaround or "ownership" here? Thank.

PersistenteConfig Class

//...
@Configuration
@EnableTransactionManagement
@PropertySource({"classpath:/foo/bar/persistence-mysql.properties"})
@ComponentScan({"foo.bar" })

        //...
               @Bean
               @Autowired
               public HibernateTransactionManager transactionManager(SessionFactory sessionFactory) {
                  HibernateTransactionManager txManager = new HibernateTransactionManager();
                  txManager.setSessionFactory(sessionFactory);

                  AuditLogInterceptorImpl interceptor = new AuditLogInterceptorImpl();
                  txManager.setEntityInterceptor(interceptor);
                  return txManager;
               }
        //...

      

AuditLogInterceptorImpl Class

//...
    @Service
    @Transactional
    public class AuditLogInterceptorImpl extends EmptyInterceptor {

        private static final long serialVersionUID = 1L;

        @Autowired // <== NOT WORKING HERE... :o (object is null at runtime)
        EventsService eventsService;

//...

      

0


source to share


1 answer


Your interceptor is not configured as a Spring managed bean when instantiated this way. Try the following, making the interceptor a managed (and thus injected) bean:

PersistenteConfig Class



//...
@Configuration
@EnableTransactionManagement
@PropertySource({"classpath:/foo/bar/persistence-mysql.properties"})
@ComponentScan({"foo.bar" })

        //...
               @Bean
               public AuditLogInterceptor auditLogInterceptor() {
                   return new AuditLogInterceptorImpl();
               }

               @Bean
               @Autowired
               public HibernateTransactionManager transactionManager(SessionFactory sessionFactory) {
                  HibernateTransactionManager txManager = new HibernateTransactionManager();
                  txManager.setSessionFactory(sessionFactory);

                  txManager.setEntityInterceptor(auditLogInterceptor());
                  return txManager;
               }
        //...

      

0


source







All Articles