I. Events (Application event)
Spring events provide support for message communication between beans and beans. When a bean finishes a task and wants another bean to know and handle it, we need another bean to listen to what the current bean is sending.
The spring events need to follow the following process:
(1) Custom events, integrated applicationevent.
(2) Define the event listener to implement Applicationlistener.
(3) Publish events using containers.
Example:
1. Customize the event.
Packagecom.ecworking.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; }}
2. Event Listener.
Packagecom.ecworking.event;ImportOrg.springframework.context.ApplicationListener;Importorg.springframework.stereotype.Component; @Component Public classDemolistenerImplementsapplicationlistener<demoevent> {//implements the Applicationlistener interface and specifies the type of event to listen on. Public voidOnapplicationevent (Demoevent event) {//the message is accepted for processing using the Onapplicationevent method. String msg =event.getmsg (); System.out.println ("Bean-demolistener received a message from Bean-demopublisher:" +msg); }}
3. Event Publishing class.
Packagecom.ecworking.event;Importorg.springframework.beans.factory.annotation.Autowired;ImportOrg.springframework.context.ApplicationContext;Importorg.springframework.stereotype.Component; @Component Public classdemopublisher {@Autowired applicationcontext applicationcontext;//inject ApplicationContext to publish events. Public voidPublish (String msg) {applicationcontext.publishevent (NewDemoevent ( This, msg));//use Applcationcontext's Publishevent method to publish. }}
4. Configure the class.
Package com.ecworking.event; Import Org.springframework.context.annotation.ComponentScan; Import org.springframework.context.annotation.Configuration, @Configuration @componentscan (" Com.ecworking.event ")publicclass eventconfig {}
5. Run.
Packagecom.ecworking.event;ImportOrg.springframework.context.annotation.AnnotationConfigApplicationContext; Public classMain { Public Static voidMain (string[] args) {Annotationconfigapplicationcontext context=NewAnnotationconfigapplicationcontext (EventConfig.class); Demopublisher Demopublisher= Context.getbean (demopublisher.class); Demopublisher.publish ("Hello Application Event"); Context.close (); }}
Operation Result:
Spring Boot Combat Notes (iv)--Spring Common configuration (event application)