EventObject, the base class for event types provided for Javase, any custom events are inherited from the class, such as the gray-to-right events in the middle. Subclass Applicationevent for this interface is provided in spring.
EventListener provides an event listener interface for Javase, and any custom event listener implements the interface, such as the individual event listeners on the left. The subclass Applicationlistener interface for this interface is provided in spring.
The role class for event publishers is not available in javase, and the role of event publishers is implemented by each application itself. The Applicationeventpublisheraware interface is provided as the event Publisher in spring.
1. Writing Events
Public classMyEventextendsapplicationevent {/** * */ Private Static Final LongSerialversionuid = -1002815320277254124l; PrivateString MethodName; PublicMyEvent (Object source) {Super(source); } PublicMyEvent (Object source, String methodName) {Super(source); This. MethodName =MethodName; } PublicString Getmethodname () {returnMethodName; } Public voidsetmethodname (String methodName) { This. MethodName =MethodName; }}
2, write the Event monitor listener
Public class Implements Applicationlistener<applicationevent> { @Override publicvoid Onapplicationevent (Applicationevent event) { ifinstanceof myevent) { MyEvent Event2=(myevent) event; System.out.println ("Execute custom Event!") +event2.getmethodname ()); }}}
3. Write Event Publishers
Public classMyPublisherImplementsApplicationeventpublisheraware {PrivateApplicationeventpublisher Applicationeventpublisher; @Override Public voidSetapplicationeventpublisher (Applicationeventpublisher applicationeventpublisher) { This. applicationeventpublisher=Applicationeventpublisher; } Public voidMethodtomonitor () {applicationeventpublisher.publishevent (NewMyEvent ( This, "AAA")); Applicationeventpublisher.publishevent (NewMyEvent ( This, "BBB")); } }
4. Testing
Public Static void Main (string[] args) { new classpathxmlapplicationcontext ("classpath:spring/ Applicationcontext.xml "); MyPublisher mypublisher=applicationcontext.getbean ("MyPublisher", MyPublisher. Class); Mypublisher.methodtomonitor ();}
Output
Execute custom Events! AAA performs custom event !BBB
Spring publishes and receives events