I am using Java ApplicationEvents to publish and then subscribe listen to an event. What is the difference between @EventListener
annotation and ApplicationListener
interface. Any differences, or the same functionality?
Resource: https://reflectoring.io/spring-boot-application-events-explained/
Method 1:
@Component
class UserRemovedListener {
@EventListener(condition = "#event.name eq 'reflectoring'")
void handleConditionalListener(UserRemovedEvent event) {
// handle UserRemovedEvent
}
}
Method 2:
@Component
class UserCreatedListener implements ApplicationListener<UserCreatedEvent> {
@Override
public void onApplicationEvent(UserCreatedEvent event) {
// handle UserCreatedEvent
}
}
Based on the document, they are almost the same
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
But if you use @EvenListener, it will automatically register the ApplicationListener. The whole quote are:
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
In the official site, the doc also explains that the annotation make it easier to use + shorter. The link should be: https://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/context/event/EventListener.html
Hope this help.