Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What are the advantages of using Spring application event publishing?

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?

like image 306
stevebot Avatar asked Mar 08 '11 23:03

stevebot


People also ask

Which method is used to publish your own custom event in spring?

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(....) .

Which of the following events is published when the application context is prepared?

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.

What is application Level Events in spring?

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.


1 Answers

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:

  • you might in future need to take more than one independent action when the event occurs
  • the processing needs to be handed off to another thread to prevent blocking, e.g. sending an email (using a custom ApplicationEventMulticaster).
  • how the system handles the event, e.g. AuthorizationFailureEvent, does not depend on the outcome of the listeners.
  • You are writing a library, e.g. Spring Security, and direct API calls are not an option.
like image 172
Barry Pitman Avatar answered Sep 20 '22 20:09

Barry Pitman