Spring events provide support for message communication between beans and beans, and when a bean finishes a task and wants another bean to know and handle it, then we need to have a bean listen to the events sent by the current bean.
The spring events need to follow the following process:
- Custom events, integrated applicationevent.
- Define event listeners to implement Applicationlistener.
- Publish events using containers.
One, custom events
Packagecom.cenobitor.appevent.event;Importorg.springframework.context.ApplicationEvent; Public classDemoeventextendsapplicationevent {Private Static Final LongSerialversionuid = 1L; PrivateString msg; Publicdemoevent (Object source,string msg) {Super(source); This. msg =msg; } PublicString getmsg () {returnmsg; } Public voidsetmsg (String msg) { This. msg =msg; }}
Second, the event listener
PackageCom.cenobitor.appevent.listener;Importcom.cenobitor.appevent.event.DemoEvent;ImportOrg.springframework.context.ApplicationListener;Importorg.springframework.stereotype.Component;
//Implement the Applicationlistener interface and specify the type of event to listen on @Component Public classDemolistenerImplementsApplicationlistener<demoevent>{@Override
//Use the Onapplicationevent method to receive messages for processing Public voidonapplicationevent (demoevent demoevent) {String msg=demoevent.getmsg (); System.out.println ("(Bean-demolistener) received a message from Bean-demopublisher:" +msg); }}
Third, the event release class
PackageCom.cenobitor.appevent.publisher;Importcom.cenobitor.appevent.event.DemoEvent;Importorg.springframework.beans.factory.annotation.Autowired;ImportOrg.springframework.context.ApplicationContext;Importorg.springframework.stereotype.Component; @Component Public classDemopublisher {@Autowired
//inject ApplicationContext to publish events ApplicationContext ApplicationContext; //Use ApplicationContext's Publishevent method to publish Public voidPublish (String msg) {applicationcontext.publishevent (NewDemoevent ( This, msg)); }}
Four, the operation
Packagecom.cenobitor.appevent;ImportCom.cenobitor.appevent.publisher.DemoPublisher;ImportOrg.springframework.context.annotation.AnnotationConfigApplicationContext; Public classMain { Public Static voidMain (string[] args) {Annotationconfigapplicationcontext context=NewAnnotationconfigapplicationcontext (appeventapplication.class); Demopublisher Demopublisher= Context.getbean (demopublisher.class); Demopublisher.publish ("Hello Application Event"); Context.close (); }}
Result: (Bean-demolistener) received a message from Bean-demopublisher: Hello Application Event
Note: Excerpt from the "Java EE Development Subversion springboot combat."
Springboot-Events (Application event)