I work on a web app that uses some Spring Application Event publishing and I was wondering what the advantages of it are? Why not just create a service call for everything that happens in the event handler's onApplicationEvent
, and then call that service in place of publishing the event?
To publish custom events, we will need an instance of ApplicationEventPublisher and then call the method ApplicationEventPublisher#publishEvent(..) . Another way to publish event is to use ApplicationContext#publishEvent(....) .
Class ApplicationContextInitializedEvent Event published when a SpringApplication is starting up and the ApplicationContext is prepared and ApplicationContextInitializers have been called but before any bean definitions are loaded.
Spring core framework provides application-level event firing on loading the beans. The ApplicationContext publishes certain types of events on different types of loaded beans. The pattern behind Spring Application Events firing and event listening is Observer Design Pattern.
One of the advantages to using Spring's event publishing (observer pattern - http://en.wikipedia.org/wiki/Observer_pattern) is that the components are loosely coupled - there is no direct coupling between the publisher and the subscriber. Sure, they both have a dependency on the Spring Event API, but not on each other. This makes it possible to extend the application by adding/removing subscribers without affecting other subscribers (assuming that your subscribers don't depend on each other).
On the other hand, as you might have found, it can make debugging more tricky because it introduces a level of indirection between the source of an event and the overall outcome.
Yes, you can usually replace an event with a direct API call. Using Events are a good fit when:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With