java - Spring 中的异步 ApplicationListener 与异步 @EventListener 的比较
问题描述
由于在 Spring 4.2 版本中添加了 Annotation-Driven Event Listener,因此要制作异步事件侦听器,只需将@Async
annotation 添加到使用 .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());
}
}
我已经尝试过了,它可以正常工作,但我不确定这是否是一个好习惯或会导致问题。
提前致谢。
解决方案
推荐阅读
- android - 为什么android studio不显示代码错误所在的行?
- sql - 使用 group by 取消嵌套多个列
- c++ - NDK 编译器找不到“对”模板
- sas - 如何解决sas中未声明的数组引用错误?
- spring-tool-suite - 如何修复 sts 4 application.properties 内容辅助
- google-sheets - 如何从导入的表中删除不必要的列
- docker - traefik+docker-compose 无法获取让我们加密子域的证书
- cmake - cmake 如何找到我的 llvm cmake 配置?
- android - Chrome 移动渐进式网络应用在离线时返回错误
- android - 没有互联网时,Firebase 抛出 FirebaseException 而不是 FirebaseNetworkException