zoukankan      html  css  js  c++  java
  • Spring中的事件监听实现

    在spring中我们可以自定义事件,并且可以使用ApplicationContext类型对象(就是spring容器container)来发布这个事件
    事件发布之后,所有的ApplicaitonListener(监听器)实例都会被触发并调用指定方法onApplicationEvent()来处理.

    这里的ApplicationEvent继承于Java中的EventObject,隶属于事件对象

    ApplicaitonListener继承于Java中的EventListener,隶属于监听者对象

    例如:
    自定义事件类RainEvent:

    public class RainEvent extends ApplicationEvent {
    public RainEvent(Object source) {
    super(source);
    }
    }

    监听器类RainListener1

    public class RainListener1 implements ApplicationListener<RainEvent>{
    
    @Override
    public void onApplicationEvent(RainEvent event) {
    System.out.println("唐僧大喊:" + event.getSource() + "赶快收衣服喽!");
    }
    
    }

    监听器类RainListener2

    public class RainListener2 implements ApplicationListener<RainEvent>{
    
    public void onApplicationEvent(RainEvent event) {
    System.out.println("我们:" + event.getSource() + "太好了不用上课了!");
    }
    }

    xml文件:

    <!-- 只需要把这俩个监听器类交给spring容器管理就可以了 -->
    <bean class="com.briup.ioc.event.RainListener1"></bean>
    <bean class="com.briup.ioc.event.RainListener2"></bean>

    测试:

    main:
    String path = "com/briup/ioc/event/event.xml";
    ApplicationContext container = new ClassPathXmlApplicationContext(path);
    //发布事件
    container.publishEvent(new RainEvent("下雨了!"));
  • 相关阅读:
    miniport hook ethFilterDprIndicateReceivePacket 接收拦截时包处理问题
    XRename(文件文件夹超级重命名工具)简介
    正则表达式测试工具
    很好看的表格样式
    FillForms 1.2.9 preliminarily reviewed
    CSDN分页ID提取工具(vb编写)
    html表格样式等整理
    备忘录
    巧用正则巅峰采集黄金白银大盘价信息
    2011年个人奋斗目标
  • 原文地址:https://www.cnblogs.com/Magic-Li/p/11769887.html
Copyright © 2011-2022 走看看