我有一个 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)
您对为什么 publisher
为 null
有什么建议吗?
最佳答案
如果您在没有 Bean 帮助的情况下创建了 CustomeEvent
(例如 CustomEvent event = new CustomEvent()
.
相反,在配置 (Spring) 中将 CustomEvent
声明为 bean,并使用应用程序上下文获取 CustomEvent
。
关于spring - ApplicationEventPublisher 没有被 Autowiring 到组件中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46957527/