Thursday, October 22, 2009

Event Driven Programming with Java - Monsoon

I've recently been involved on an Adobe Flex project at work. One of the things that I've really come to enjoy about Flex is its powerful event framework. For instance, component A can say that it throws an OnSave event. Component B says it listens for OnSave events. Neither component has to know anything about each other, but when component A throws the event, B will automatically handle it.

If you've been around Java for any length of time, you may have done some AWT or Swing development. Here, we have a similar concept of events, but each listener has to register itself with whatever object might throw that event. In the end, you end up with a tightly coupled web of connections and dependencies that, if not managed correctly, can quickly become a nightmare to maintain.

Enter Monsoon. I know that there are other event frameworks available, but could not find any that did exactly what I wanted (granted I didn't search that hard). I also thought this would be an interesting challenge. The idea is that all of the event plumbing is handled automatically via Java 1.5 Annotations. An 'event' in this system can be any java object (POJO). Methods that dispatch and listen for events both have the @Event annotation. The return object from a dispatch method is used as the method parameter of the listening method. For Example:

@Event(name="saveUser", type=EventType.DISPATCHER)
public User save()
  return user;

@Event(name="saveUser", type=EventType.LISTENER)
public void onSave(User user)
  //do something with user

If you're using Spring, configuration is trivial. Just include an 'EventBeanPostProcessor' bean in your spring config.

<bean class="org.jthompson.monsoon.spring.EventBeanPostProcessor">
  <property name="managedBeanNames">

Otherwise, you'll need to use the included ObjectFactory to generate your objects if you aren't using spring.

Dispatcher dispatcher = (Dispatcher)factory.generateProxy(new Dispatcher());

Monsoon will automatically discover the connections between dispatchers and listeners for you. If you register three object that listen for a particular event, they will all be triggered automatically.

This is still in an early phase of development and there is a lot of work yet to do. However, if you find it useful or interesing in the least please let me know!

You can get the latest version of Monsoon via maven here:

You can also browse the source code at my googlecode page:

No comments:

Post a Comment