ApplicationEventPublisher未自动装配到Component中

时间:2017-10-26 14:52:42

标签: 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)

您对publisher null的原因有什么建议吗?

2 个答案:

答案 0 :(得分:0)

如果CustomEvent在Spring的包扫描中,那么我不知道。

但是,还有一个额外的解决方案。

创建一个类来实例化spring托管类,但是通过 ApplicationContext

1 - 创建以下课程:

public class AppContextUtil implements ApplicationContextAware {

    private static ApplicationContext context;

    @Override
    public void setApplicationContext(ApplicationContext appContext) throws BeansException {
        context = appContext;
    }

    public static ApplicationContext getApplicationContext() {
        return context;
    }

    public static <T> T getBean(Class<T> classe) {
        return context.getBean(classe);
    }

}

2 - 实例类如下:

public class CustomEvent {

    private ApplicationEventPublisher publisher;

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

    private ApplicationEventPublisher getApplicationEventPublisher() {
        return AppContextUtil.getBean(ApplicationEventPublisher.class);
    }

}

答案 1 :(得分:0)

ApplicationEventPublisher的初始化不会发生,或者如果您在没有Bean的帮助下创建了CustomeEvent(例如CustomEvent event = new CustomEvent()),则将保持为空。

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