Java 应用程序事件 : Difference between @EventListener annotation and ApplicationListener interface

标签 java spring spring-boot events event-listener

我正在使用 Java ApplicationEvents 来发布然后订阅监听事件。 @EventListener 注解和 ApplicationListener 接口(interface)有什么区别。有什么区别或相同的功能吗?

资源:https://reflectoring.io/spring-boot-application-events-explained/

方法一:

@Component
class UserRemovedListener {

  @EventListener(condition = "#event.name eq 'reflectoring'")
  void handleConditionalListener(UserRemovedEvent event) {
    // handle UserRemovedEvent
  }
}

方法2:

@Component
class UserCreatedListener implements ApplicationListener<UserCreatedEvent> {

  @Override
  public void onApplicationEvent(UserCreatedEvent event) {
    // handle UserCreatedEvent
  }
}

最佳答案

根据文档,它们几乎相同

There are two ways to define a listener. We can either use the @EventListener annotation or implement the ApplicationListener interface. In either case, the listener class has to be managed by Spring.Blockquote

但是如果你使用@EvenListener,它会自动注册ApplicationListener。整个报价是:

Starting with Spring 4.1 it’s now possible to simply annotate a method of a managed bean with @EventListener to automatically register an ApplicationListener matching the signature of the method

在官方网站中,文档还解释说注释使其更易于使用并且更短。链接应该是:https://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/context/event/EventListener.html

https://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/context/ApplicationListener.html

希望这有帮助。

关于Java 应用程序事件 : Difference between @EventListener annotation and ApplicationListener interface,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/77463574/

相关文章:

java - 当文件夹中没有文件时 Camel 停止

java - IntelliJ插件开发: A context item is shown in IDEA but not in WebStorm

java - 获取 .jar 文件旁边的文件夹的位置

java - 您是否成功地使用了 Spring 和 Hibernate Web 应用程序

java - Java中从json中获取键值 - JSON解析

java - 为什么这两种素数采样方法运行的时间一样长?

java - Spring 隐藏的自定义 Java 注解

java - 了解 Spring JPA 底层原生查询

spring - 多个 application.yml 未在 Spring Boot 中合并

java - 使用 java 8 和服务注入(inject)的策略模式