One of the most powerful features of the Spring framework is its Application Events feature, which allows
developers to create custom event-driven applications. Spring Application Events are events that are triggered
by the Spring framework. They are designed to be used in the development of applications that need to be aware
of changes in the environment. Spring Application Events allow developers to create applications that can respond
to changes in the application environment in real time. Spring Application Events are based on the concept of the
Observer pattern. The Observer pattern is a design pattern in which an object is able to observe the state of another
object and react accordingly. In the case of Spring Application Events, the observer is the application and the object
being observed is the application environment. It helps in improving code reusability. It is great tool for async
intra-microservice-communication, just like we do async inter-microservice-communication using Kafka.
Spring Application Events don't require any specific dependencies, just the application with spring-web will do.
Say, we are building Hospital Management System, and we are suppose to build discharge-patient-service.
Which requires -
Billing Service => Finalize the patient's bill,
Record Service => updating their medical records,
Housekeeping Services => to prepare the room for next patient,
Notification Service => to send a notification to patient and relevant medical staffs.
//Conventional way of calling methods.
/* billingService.processBill();
medicalRecordsService.updatePatientHistory();
housekeepingService.cleanAndAssign();
notificationService.notifyPatients();
*/
// find the spring-boot-application-events implementation code from github repository
-
Why we opt Spring Event then, what issue it solves? Above piece of code has issue of Tight Coupling, can't be async call, difficult to extend, maintain or test. Spring Application Event Solves it.
-
Use Postman as client to invoke discharge-service of hospital management -
-
Run the springboot code, and then go to POSTMAN.
-
Hit a POST request with
-
Body =>
{
"patientId":"B278TR279",
"patientName":"Aadi"
}
- Find your Billing Service, HouseKeeping Service, Medical Records Service, Notification Service updates in console.