Spring Events (Application event) adds support for message communication between beans and beans, and when a bean finishes a task, it wants the other bean to know and handle it accordingly. Then we need another bean to listen to the events sent by the current bean.
The spring events need to follow the following process:
(1) Custom event: Inherit Applicationevent
(2) Defining event listeners: Implementing Applicationlistener
(3) Using containers to publish events
Here is the demo
Event class
/*** * *@ClassName (class name): Demoevent (custom event) *@Description (description): Spring event provides support for message communication between beans and beans, and can be used to listen for events sent by the current bean with a bean@author (author): Wu Gui *@date (development date): November 22, 2017 3:30:04 * * * *PublicClassDemoeventExtendsapplicationevent{private Static final long serialversionuid = 1L; Private String msg; public void SysLog () {System.out.println (msg);} public demoevent (Object source,string msg) { super (source); this.setmsg (msg);} Public String getmsg () { return msg;} Public void setmsg (String msg) { this.msg = msg;}}
Listening class
/*** * * @ClassName (class name): Demolistener * @Description (description): Event listener * Implements Applicationlistener and develops event types for listening * @author (author): Wu Gui * @date (development date): November 22, 2017 pm 3:35:37 * */ @Componentpublic class demolistener implements Applicationlistener<demoevent>{/*** * Receive processing of messages */ @Override public void Onapplicationevent (Demoevent event) {String msg = event.getmsg (); System.out.println ( "Demolistener received a message from Demopublisher:" +msg);}}
Publish class
/*** * * @ClassName (class name): Demopublisher * @Description (description): Event Publishing class * @author (author): Wu Gui * @date (development date): November 22, 2017 pm 3:41:13 * */ @Component public class demopublisher { @Autowired applicationcontext context; public void published () {DemoEvent event = new demoevent (this, "released successfully! "); System.out.println ( "Hair" event: "+event"); Context.publishevent (event);}}
Test class
@Configuration@ComponentScan({"com.wugz.app"})public class EventConfig { public static void main(String[] args) { AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(EventConfig.class); DemoPublisher publisher = context.getBean(DemoPublisher.class); publisher.published(); context.close(); }}
Spring's Listener Events Applicationlistener and applicationevent usage