Why HibernateTransactionManager doesn't autowi

2019-09-10 17:02发布

问题:

In an Interceptor class for automatically audit Hibernate CRUD operations, @Autowired annotation from Spring is not working.

I supose that it is due to, at configuration time, Spring doesn't have had time to configure autowiring stuff yet. In other classes everything is doing well. Is there a workaround or a "right-to-do" here? Thanks.

Class PersistenteConfig

//...
@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;
               }
        //...

Class AuditLogInterceptorImpl

//...
    @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;

//...

回答1:

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

Class PersistenteConfig

//...
@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;
               }
        //...