`
眼光独到
  • 浏览: 63482 次
  • 性别: Icon_minigender_1
  • 来自: 重庆
社区版块
存档分类
最新评论

解构Spring事件体系及具体实现

阅读更多

Spring的ApplicationContext能够发布时间并且允许注册相应的事件监听器,因此他拥有一套完善的事件发布和监听机制。在事件体系中,除了事件和监听器以外,还有另外三个重要的概念:

   1)事件源:时间的产生者,任何一个EventObject都必须拥有一个事件源;

   2)事件监听器注册表:组件或框架的事件监听器必须有所依存,也就是说组件或框架必须提供一个地方保存时间监听器,这便是事件监听器注册表。一个事件监听器注册到组件或框架中其实就是保存在监听器注册表里面;

   3)它是事件和事件监听器沟通桥梁,负责把事件通知给事件监听器。

    Spring框架本身定义了三个事件,

    1) ContextRefreshedEvent:当容器初始化或者刷新时产生该事件,就是调用容器的refresh()方法时会产生该事件;

    2) ContextClosedEvent:当容器关闭前产生该事件,即调用容器的close()方法时就会产生该事件;

    3)RequestHandleEvent:这是一个与Web应用相关的事件,当一个HTTP请求被处理后,产生该事件。只有在web.xml中定义了DispatcherServlet时才产生该事件。

    我们也可以扩展ApplicationEvent定义自己的事件,完成其他特殊功能。

    自定义一个事件监听器 代码如下:

 

该事件继承ApplicationEvent类

public class MailSendEvent extends ApplicationEvent{
 private String to;
 public MailSendEvent(Object source,String to) {
  super(source);
  this.to = to;
  System.out.println("实例化MailSendEvent");
 }
 public String getTo(){
  return this.to;
 }
}


该监听器实现了ApplicationListener接口,并实现其中的onApplicationEvent方法。event instanceof MailSendEvent 表明该监听器只能监听到 MailSendEvent事件。

public class MailSendListener implements ApplicationListener{
 public MailSendListener(){
  System.out.println("实例化监听器");
 }
 public void onApplicationEvent(ApplicationEvent event) {
  if(event instanceof MailSendEvent){
   MailSendEvent mse = (MailSendEvent)event;
   System.out.println("MailSendListener:向"+mse.getTo()+"发送完一封邮件");
  }
 }
}

 

ApplicationContextAware接口是在实例化MailSender只有调用,setApplicationContext()方法在此处注入ApplicationContext 对象,sendMail()方法中 ctx.publishEvent(mse); 向容器中所有的事件监听器发送事件,所以调用该方法后会激活监听该事件的事件监听器,而此事件是mse即MailSendEvent,所以将被MailSendListener 监听到。

public class MailSender implements ApplicationContextAware{
 private ApplicationContext ctx;
 public void setApplicationContext(ApplicationContext ctx)
   throws BeansException {
  this.ctx = ctx;
  System.out.println("调用ApplicationContextAware接口方法");
 }
 public void sendMail(String to){
  System.out.println("MailSender:模拟发送邮件");
  MailSendEvent mse = new MailSendEvent(this, to);
  //向容器中所有的事件监听器发送事件
  ctx.publishEvent(mse);
 }
}

 

调用发送,启动事件,激活事件监听器。

public class MailSend {
 public static void main(String[] args) {
  ApplicationContext ctx = new ClassPathXmlApplicationContext("com/Spring/event/beans.xml");
  MailSender mailSender = (MailSender)ctx.getBean("mailSender");
  //mailSender.setApplicationContext(ctx);
  mailSender.sendMail("songbo_mail@126.com");
 }
}


 

配置文件表示当容器启动时,会根据此配置信息自动注册MailSendListener监听器。

 <bean class="com.Spring.event.MailSendListener"></bean>
 <bean id="mailSender" class="com.Spring.event.MailSender"></bean>

 

 

解构Spring事件体系及具体实现


分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics