Vishwanath Krishnamurthi's blog

A blog on Java EE, clean code, open source and TDD

How to publish and subscribe to events with Spring ?

leave a comment »

What do we need ?

There are three classes that we’d require:

  1. An event class
  2. A listener
  3. A publisher


  1. With Spring, you can write your own event class by extending ‘ApplicationEvent
  2. A listener is just a bean that implements ‘ApplicationListener
  3. And finally a class that triggers an event –

      >  Here we have choices:

A design tip:

Your listener class would have to implement ApplicationListener. Now it would start listening to all the ApplicationEvents. Rather make it listen only to the concerened event by making it implement ApplicationListener<TheConcernedEvent>.

Type parameters are cool aren’t they ?

A testing tip:

How to trigger the event from JUnit. We need a context, right ?  StaticApplicationContext comes in pretty handy here.

StaticApplicationContext context=new StaticApplicationContext();
context.addApplicationListener(new YourEventListener());
context.publishEvent(new YourEvent());

With StaticApplicationContext used, we are not forced to load any beans that are not required from a config file. Saves time 🙂


Written by Vishwanath Krishnamurthi

June 15, 2011 at 8:37 pm

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s

%d bloggers like this: