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.