spring - ApplicationEventPublisher 没有被 Autowiring 到组件中

标签 spring hibernate events spring-boot autowired

我有一个 Spring Boot 应用程序和 @Component 类,如下所示:

@Component
public class CustomEvent {

    @Autowired
    ApplicationEventPublisher publisher;

    @PreRemove
    public void onItemDelete(Object entity) {
        System.out.println(" =======PUBLISH====== " + entity);
        publisher.publishEvent(new EntityDeleteEvent<>(entity));
    }
}

当它运行上述方法时,第一行会打印出正确的实体,但 publisher.publishEvent 行会抛出 NullPointerException。我认为 ApplicationEventPublisher 不是 @Autowired 但找不到原因。应用程序中的其他 @Components@ComponentScanner 找到。

当然,在我的实体中,这个 CustomEvent 已注册:

@Entity
@EntityListeners(
        CustomEvent.class
)
@Data
@AllArgsConstructor
public class Item 

抛出的确切错误如下所示:

2017-10-26 16:46:06.190 ERROR 10176 --- [io-8091-exec-10] o.a.c.c.C.[.[.[/].[dispatcherServlet]    : Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed; nested exception is java.lang.NullPointerException] with root cause
java.lang.NullPointerException: null
    at com.inventory.events.CustomEvent.onItemDelete(CustomEvent.java:19)

您对为什么 publishernull 有什么建议吗?

最佳答案

如果您在没有 Bean 帮助的情况下创建了 CustomeEvent(例如 CustomEvent event = new CustomEvent().

相反,在配置 (Spring) 中将 CustomEvent 声明为 bean,并使用应用程序上下文获取 CustomEvent

关于spring - ApplicationEventPublisher 没有被 Autowiring 到组件中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46957527/

相关文章:

java - 在不同的 Spring 上下文中加载属性

java - Hibernate 无法解析属性

sql - 在gral HQL中,我将如何使用(非聚合的)Oracle函数?

javascript - Electron 浏览器窗口中需要“onShow”事件

javascript - MS Edge 无法检测 <use> SVG 元素的委托(delegate)事件?

java - 如何使用 Spring-data-Redis 实现 Redis Multi-Exec

java - 从 .properties 文件加载消息时出错

java - 需要带有建议和切入点的@Transactional

hibernate - 使用 hibernate hbm2ddl.auto=update : How can I alter column not to require value anymore?

c# - 如何在引发另一个事件时引发一个事件?