开发者

What are the advantages of using Spring application event publishing?

开发者 https://www.devze.com 2023-02-15 11:29 出处:网络
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 happen

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?


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.


In answer to the part of the question that asks why not just create a service call; because someone else has already written the code, documented it and tested it.


Use Cases of Event-based Listener -

  1. TDD becomes very handy(which in turn will eliminate bugs)

  2. Best suited for Single Responsibility pattern (clean code) (Link for reference - https://www.youtube.com/watch?v=h8TWQM6fKNQ)

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号