生活中的例子:自己调好闹钟,让闹钟叫醒自己,让闹钟去监听时间
在spring中我们可以自定义事件类继承ApplicationEvent,并且可以使用ApplicationContext类型的对象去发布这个事件,发布完成之后,所有的ApplicationListener(监听器)实例都会被触发并调用指定的方法onApplicatioinEvent()来处理
事件类
//自定义事件类RainEvent:下雨事件,,继承ApplicationEvent表示是一个事件
public class RainEvent extends ApplicationEvent {//继承事件类
public RainEvent(Object source) {
super(source);
}
}
监听器1
//监听器,泛型表示监听的那个事件,这里是RainEvent类
// 监听器类RainListener1实现ApplicationListener,并监听的是指定的RainEvent类
public class RainListener1 implements ApplicationListener<RainEvent>{//继承监听类
@Override
public void onApplicationEvent(RainEvent event) {
//当监听到发布的事件时需要执行的操作
System.out.println("唐僧大喊:" + event.getSource() + "赶快收衣服喽!");
}
}
监听器2
//监听器2
public class RainListener2 implements ApplicationListener<RainEvent>{//继承监听类
@Override
public void onApplicationEvent(RainEvent event) {
//当监听到发布的事件时需要执行的操作
System.out.println("我们:" + event.getSource() + "太好了不用上课了!");
}
}
event.xml
只需要放到内存中,会一直处于监听状态
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.2.xsd">
<!-- 只需要把这两个监听器类交给spring容器管理就可以了 -->
<!-- 监听器,是一直处于监听状态,直到获取到对应事件源 只需要定义class-->
<bean class="com.briup.ioc.event.RainListener1"></bean>
<bean class="com.briup.ioc.event.RainListener2"></bean>
</beans>
测试类中:
//知识点: 自定义事件
@Test
public void ioc_event() {
try {
String path = "com/briup/ioc/event/event.xml";
ApplicationContext container = new ClassPathXmlApplicationContext(path);
//需要监听器执行代码时就发布事件
container.publishEvent(new RainEvent("下雨了!"));//发布事件
} catch (Exception e) {
e.printStackTrace();
}
}
结果: