Spring Events

Spring Events

We will be discussing how to use events in Spring and will learn annotation-driven event listeners. In Spring, event publishing is the capability provided by ApplicationContext.

Few things to remember:
1] Event class should extend ApplicationEvent
2] Publisher class should have ApplicationEventPublisher object injected
3] Listener class should implement ApplicationListener interface

Consider a scenario where you have to trigger an email after any type of entity is created. An entity could be a user, project, organization, deal, task.
So the flow would be something like:
1] New entity has been created/saved in the database.
2] Create new entity created event which will be published by ApplicationEventPublisher.
3] ApplicationListener class will listen to the event and will create/send an email.

Suppose you are creating a Project. Project structure would like this:

Create Event class which extends ApplicationEvent. We are creating generic event class to handle multiple entities like projects, users, tasks etc.

Publish event after an entity is created.

Listen to the event and send mail after an entity is created.

In this tutorial we went over the basics of events in Spring – creating a simple, custom event, pushing it and then handling it in a listener. There is support for async processing as well. You learn more about Spring Events, visit this site.


Leave a Reply

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

WordPress.com Logo

You are commenting using your WordPress.com 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