首页 > 解决方案 > Spring 中的异步 ApplicationListener 与异步 @EventListener 的比较

问题描述

由于在 Spring 4.2 版本中添加了 Annotation-Driven Event Listener,因此要制作异步事件侦听器,只需将@Asyncannotation 添加到使用 .annotation 注释的公共方法中@EventListener

@Component
public class AnnotationDrivenContextStartedListener {

    @Async
    @EventListener
    public void handleContextStart(ContextStartedEvent cse) {
        System.out.println("Handling context started event.");
    }

}

问题如下。是否可以将@Async注释添加到onApplicationEvent传统的方法中ApplicationListener以实现相同的功能?或者我们应该定义一个新的 bean 以ApplicationEventMulticaster异步方式处理所有事件?

@Component
public class CustomSpringEventListener implements ApplicationListener<CustomSpringEvent> {

    @Async
    @Override
    public void onApplicationEvent(CustomSpringEvent event) {
        System.out.println("Received spring custom event - " + event.getMessage());
    }

}

我已经尝试过了,它可以正常工作,但我不确定这是否是一个好习惯或会导致问题。

提前致谢。

标签: javaspringspring-booteventsevent-listener

解决方案


推荐阅读