You need to enable JavaScript to run this app. Spring Boot中Hibernate EventListener内@Autowired注入服务为空如何解决
优惠活动
大模型
产品
解决方案
定价
更多

Spring Boot中Hibernate EventListener内@Autowired注入服务为空如何解决

问题根因

EntityEventListener虽然添加了@Service注解注册到Spring容器,但你在EntityIntegrator中是手动通过new EntityEventListener()创建的实例,该实例不归Spring管控,因此@Autowired注解不会生效,commonService自然为空。

修复步骤

1. 改造EntityIntegrator为Spring管理的Bean

删除硬编码的静态单例,改为通过构造函数注入Spring已经完成依赖注入的监听器实例:

@Component
public class EntityIntegrator implements Integrator {

    private final EntityEventListener entityEventListener;

    // Spring自动注入已完成属性装配的监听器
    public EntityIntegrator(EntityEventListener entityEventListener) {
        this.entityEventListener = entityEventListener;
    }

    @Override
    public void integrate(Metadata metadata, SessionFactoryImplementor sessionFactory,
                          SessionFactoryServiceRegistry serviceRegistry) {
        final EventListenerRegistry eventListenerRegistry =
                serviceRegistry.getService(EventListenerRegistry.class);
        // 直接使用注入的监听器,不再手动new
        eventListenerRegistry.appendListeners(EventType.POST_INSERT, entityEventListener);
        eventListenerRegistry.appendListeners(EventType.POST_UPDATE, entityEventListener);
    }

    @Override
    public void disintegrate(SessionFactoryImplementor sessionFactory,
                             SessionFactoryServiceRegistry serviceRegistry) {
    }
}

2. 改造PropertyConfigurer,注入Spring管理的Integrator

不再使用硬编码的单例实例,改为注入Spring容器中的EntityIntegrator:

@Configuration
public class PropertyConfigurer implements HibernatePropertiesCustomizer {

    private final EntityIntegrator entityIntegrator;

    public PropertyConfigurer(EntityIntegrator entityIntegrator) {
        this.entityIntegrator = entityIntegrator;
    }

    @Override
    public void customize(Map<String, Object> hibernateProperties) {
        hibernateProperties.put("hibernate.integrator_provider",
                (IntegratorProvider) () -> Collections.singletonList(entityIntegrator));
    }
}

3. 修正监听器代码的笔误

你代码中调用commonService时变量名拼写错误,定义时为驼峰格式commonService,调用时写成了全小写的commonservice,修正即可:

// 修正前
commonservice.test((EntityClass) event.getEntity());
// 修正后
commonService.test((EntityClass) event.getEntity());

内容的提问来源于stack exchange,提问作者Ashok Cj

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.15 22:36:03