spring容器的事件机制是通过观察者模式实现的。
spring容器的事件机制和所以的事件机制都类似,都是由事件源、事件、事件监听器组成,只不过这里的事件源是ApplicationContext(spring容器)。
spring容器的事件机制是有ApplicationEvent类和ApplicationListener接口实现的,如果容器有一个ApplicationListener Bean,当spring容器发布ApplicationEvent Bean时(初始化),ApplicationListener Bean将自动被调用。
例子:
1、EmailEent类继承ApplicationEvent类
package myspring.com.bean;
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;
}
}
2、EmailNotifier类实现ApplicationListener接口
package myspring.com.bean;
import org.springframework.context.ApplicationEvent;
import org.springframework.context.ApplicationListener;
public class EmailNotifier implements ApplicationListener {
@Override
public void onApplicationEvent(ApplicationEvent arg0) {
if(arg0 instanceof EmailEvent){
EmailEvent e = (EmailEvent)arg0;
System.out.println("邮件地址:"+e.getAddress());
System.out.println("邮件内容为:"+e.getText());
}else{
System.out.println("该事件为容器内置事件"+arg0.toString());
}
}
}
3、在bean.xml中配置监听器,和EmailEvent对象
<pre name="code" class="java"><bean class="myspring.com.bean.EmailNotifier"></bean>
<bean id = "emailEvent" class="myspring.com.bean.EmailEvent">
<constructor-arg value="hello"></constructor-arg>
<constructor-arg value="nannan22222@qq.com"></constructor-arg>
<constructor-arg value="spring event test"></constructor-arg>
</bean>
4、测试类
package myspring.com.bean;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.FileSystemXmlApplicationContext;
public class EmailEventMainMethod {
public static void main(String[] args) {
// TODO Auto-generated method stub
ApplicationContext ac = new FileSystemXmlApplicationContext("config/bean.xml");
//EmailEvent e = new EmailEvent("hello","nannan@qq.com","spring event test");
EmailEvent e_ = ac.getBean("emailEvent",EmailEvent.class);
//ac.publishEvent(e_);//监听spring容器内置事件
}
}
5、输出结果
邮件地址:nannan22222@qq.com
邮件内容为:spring event test
spring提供的几个其他内置事件:
1、ContextRefreashedEvent:spring容器初始化或者刷新触发该事件
2、ContextStartedEvent:ConfigurableApplicationContext(ApplicationContext的子接口)的start()方法启动spring容器时触发该事件
3、ContextClosedEvent:ConfigurableApplicationContext(ApplicationContext的子接口)的Close()方法关闭spring容器时触发该事件
4、ContextStopedEvent:ConfigurableApplicationContext(ApplicationContext的子接口)的stop()方法停止spring容器时触发该事件
5、RequstHandledEvent:使用spring作为MVC控制器时,spring处理用户请求结束后,触发该事件