为什么HibernateTransactionManager不会自动注入Spring注入?

时间:2015-08-20 16:04:21

标签: java spring hibernate spring-mvc

在一个用于自动审计Hibernate CRUD操作的Interceptor类中,来自Spring的@Autowired注释无效。

我认为这是因为,在配置时,Spring还没有时间配置自动装配的东西。在其他课程中,一切都很顺利。这里有解决方法还是“权利”?感谢。

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

类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 个答案:

答案 0 :(得分:0)

在以这种方式实例化时,您的拦截器未配置为托管Spring bean。尝试以下操作,使拦截器成为托管(并因此注入)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;
               }
        //...