Event Source: ApplicationContext. Publishevent () Method: used to actively trigger container events. Event: Applicationevent class, container event, must be published by ApplicationContext. Event Listener: The Applicationlistener interface, which can be held by any listener bean in the container. Onapplicationevent (Applicationevent Event): This method is triggered whenever any event occurs within the container
The container event class inherits the Applicationevent class, and the listener class of the container event implements the Applicationlistener interface.
An example is given below
1. First define a EmailEvent class, inheriting the Applicationevent class
public class EmailEvent extends Applicationevent { private String address; private String text; Public emailevent (Object source) { super (source); } Public EmailEvent (Object source, string address, string text) { super (source); this.address = address; This.text = text; } Public String getaddress () { return address; } public void setaddress (String address) { this.address = address; } Public String GetText () { return text; } public void SetText (String text) { this.text = text; }}
2, define a Emailnotifier class, implement the Applicationlistener interface, and replicate the Onapplicationevent () method
public class Emailnotifier implements Applicationlistener { @Override public void Onapplicationevent ( Applicationevent applicationevent) { if (applicationevent instanceof emailevent) { emailevent EmailEvent = ( emailevent) applicationevent; SYSTEM.OUT.PRINTLN ("Receive address to send mail:" + emailevent.getaddress ()); SYSTEM.OUT.PRINTLN ("message body to send mail:" + emailevent.gettext ()); } else { System.out.println ("event of the container itself:" + applicationevent);}}}
3. Configure the listener in the container
<bean class= "Org.spring.listener.EmailNotifier"/>
4. Writing the main program main
public class Springtest {public static void Main (string[] args) { ApplicationContext ctx = new Classpathxmlapplic Ationcontext ("Spring-config.xml");// emailevent ele = new EmailEvent ("Hello", "[email protected]", "This is a test") ;// ctx.publishevent (ele);} }
At the end of the program, the results of the operation are as follows:
Event of the container itself: org.springframework.context.event.contextrefreshedevent[source=org[email protected]b81eda8:startup Date [ Thu Dec 20:20:52 CST 2014]; Root of context hierarchy]
If you cancel the comment in main, that is, use publishevent () to trigger the event, the result is as follows:
Event of the container itself: org.springframework.context.event.contextrefreshedevent[source=org[email protected]b81eda8:startup Date [ Thu Dec 20:24:03 CST 2014]; Root of context hierarchy] need to send a message to the receiving address: [email protected] need to send the message body: This is a test
The event mechanism of Spring---applicationcontext