Suppose you are making an event-driven application. You have your listener interfaces and your event-generating objects. What is the most annoying part of getting this all to work?
Connecting your listeners to the event-generating objects. Every time you want some object to receive certain events, you have to register your listener with the correct producer object. This has some nasty effects on your code:
- Either your listeners know to which object they are subscribing, or your event generators know who should be listening to their events
- Due to this coupling, listeners and producers are difficult to test
- Adding a new listener to your project requires some boilerplate code to get it working
Spring has a feature that can take care of all of this hassle: autowiring. For normal dependency injection, autowiring feels icky. It’s just too magical and leaves me with a feeling I am not in control. The great thing about autowiring is that it can be used on a per-method base.