Spring's event mechanism The main members have these two generals
(1) Applicationevent: Container event, released by ApplicationContext
(2) Applicationlistener: Listener, which can be held by any bean in the container.
On the code.
Event class
Package com.demo.impls;
Import org.springframework.context.ApplicationEvent;
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;
}
}
Listening class
Package com.demo.impls;
Import org.springframework.context.ApplicationEvent;
Import Org.springframework.context.ApplicationListener;
The public class Emailnotifier implements applicationlistener{@Override the public
void Onapplicationevent ( Applicationevent evt) {
if (evt instanceof emailevent) {
emailevent emailevent = (emailevent) evt;
SYSTEM.OUT.PRINTLN ("Email address:" + emailevent.getaddress ());
SYSTEM.OUT.PRINTLN ("Email text:" + emailevent.gettext ());
} else{
System.out.println ("Else event:" + evt);
}
}
Beans.xml
<bean class= "Com.demo.impls.EmailNotifier" ></bean>
Test tests
Package com.test;
Import Org.springframework.context.ApplicationContext;
Import Org.springframework.context.support.ClassPathXmlApplicationContext;
Import com.demo.impls.EmailEvent;
public class Test03 {public
static void Main (string[] args) {
ApplicationContext ctx = new Classpathxmlapplicatio Ncontext ("Beans.xml");
EmailEvent evt = new EmailEvent ("WU", "wangjie@163.com", "Hello What");
Ctx.publishevent (EVT);
}
Final results
Email address:wangjie@163.com
Email Text:hello What
else EVENT:COM.DEMO.IMPLS.EMAILEVENT[SOURCE=WU]