• 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("下雨了!"));
  • 相关阅读:
    POJ-图论-最短路模板(邻接矩阵)
    POJ-图论-并查集模板
    POJ-排序-归并排序与逆序对
    【题目自解】北京大学2018计算机学科夏令营上机考试
    【算法总结】图论-拓扑排序
    【算法总结】图论-最短路径
    【算法总结】图论-最小生成树
    【算法总结】图论-并查集
    iOS程序的生命周期
    6款好用的Python IDE
  • 原文地址:https://www.cnblogs.com/Magic-Li/p/11769887.html
Copyright © 2020-2023  润新知