Listener-based dependency injection builds upon the core concepts of property-based Dependency Injection and offers many of the same benefits. Find out how you can use listener injection to reduce boilerplate code and clearly communicate relationships between POJOs using the Spring framework.
April 02, 2008
URL:http://www.drdobbs.com/the-why-and-how-behind-listener-based-de/212903214
Spring-Based Injection Example
Suppose you have an application to which you want to introduce file-based input. So you need something that will poll a directory for files being added. Enter JPoller, an open source project that has all the capabilities you need. You decide to add it to your application using Spring, which makes it easy to define an instance of your poller as well as your listener class.
JPoller defines a PollManager callback interface. You provide an instance of this interface to receive the "file found" events. The basic configuration in Spring might look as follows:
<bean id="poller" class="org.sadun.util.polling.ManagedDirectoryPoller" init-method="startUp" destroy-method="shutDown"> <property name="autoMove" value="true" /> <property name="pollInterval" value="2000" /> <property name="directories"> <list> <value>/polldir value> list> property> bean> <bean id="listener" class="example1.Callback" /> beans>
With an instance of your poller and your listener class defined, the only remaining issue is how you register your listener bean with the poller. Somewhere, your code has to call the ManagedDirectoryPoller.addPollManager() method to associate your listener with the polling object. Standard Spring effectively offers only three options for where to place this code:
All three of these approaches requires writing code, and none of them would convey exactly where the addPollManager() method is invoked just from looking at the configuration.
Enter Listener-Based dependency injection
With listener-based dependency injection you can state this relationship explicitly. Listener injection introspects the communication channels on ManagedDirectoryPoller and identifies the addPollManager(PollManager) method as a defining messaging channel (named PollManager). Just as with JavaBeans introspection, you can then register your bean with this channel by providing an appropriate listener.
I've used Spring's namespace extensions to extend the Spring XML to support syntax for injecting listeners by channel name. The example application can now fully define the relationship between poller and callback listener (see Listing 1).
Notice the line in Listing 1 containing the
This is the basic usage of listener injection, which is enough for most people to immediately see the benefit, but there really is much, much more.
Terms of Service | Privacy Statement | Copyright © 2024 UBM Tech, All rights reserved.