简体   繁体   English

如何将 spring bean 自动连接到 EventListener

[英]How to autowire spring bean into EventListener

i am searching for a way to create a listener that is also a spring component, however when i try to autowire the entity manager bean, it is always null, what am i doing wrong?我正在寻找一种方法来创建一个监听器,它也是一个 spring 组件,但是当我尝试自动装配实体管理器 bean 时,它总是 null,我做错了什么?

@Component
public class TestListener {

    @Autowired
    private TestRepository entityManager;

    @PrePersist
    @PreUpdate
    void beforeEntityUpdateOrSave(final Entity entity) {
        entityManager.someOperation() // -> NullPointerException, because the bean is "null"
    }
}

the Entity class has the listener in the @EntityListeners annotation.实体 class 在 @EntityListeners 注释中有监听器。

@EntityListeners(TestListener.class)
public class Entity 

Is the class TestRepository annotated with @Repository? class TestRepository 是否使用@Repository 进行了注释?

You could try making the field entityManager final.您可以尝试将字段 entityManager 设为最终字段。 I would also recomend using constructor injection instead.我也建议改用构造函数注入。 Field injection sometimes leads to strange behaviour.字段注入有时会导致奇怪的行为。

@Component
public class TestListener {

    private final TestRepository entityManager;

    public TestListener(@Autowired TestRepository entityManager){
        this.entityManager = entityManager;
    }

    ...

    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM