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("下雨了!"));
原文地址:https://www.cnblogs.com/Magic-Li/p/11769887.html