我正在使用 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
希望这有帮助。
关于Java 应用程序事件 : Difference between @EventListener annotation and ApplicationListener interface,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/77463574/