在spring中我们可以自定义事件,并且可以使用ApplicationContext类型对象(就是spring容器container)来发布这个事件,事件发布之后,所有的ApplicaitonListener(监听器)实例都会被触发并调用指定方法onApplicationEvent()来处理.
例如:
例如:
自定义事件类RainEvent:
//spring容器中的自定义事件
public class RainEvent extends ApplicationEvent {
public RainEvent(Object source) {
super(source);
}
}
监听器类RainListener1:
public class RainListener1 implements ApplicationListener {
public void onApplicationEvent(ApplicationEvent event) {
if (event instanceof RainEvent) {
System.out.println("唐僧大喊:" + event.getSource() + "赶快收衣服喽!");
}
}
}
监听器类RainListener2:
public class RainListener2 implements ApplicationListener {
public void onApplicationEvent(ApplicationEvent event) {
if (event instanceof RainEvent) {
System.out.println("我们:" + event.getSource() + "太好了不用上课了!");
}
}
}
上面的instanceof用法我已经在这篇:
Java instanceof关键字的详解 说过,不懂得可以去看下~
配置文件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容器管理就可以了 -->
<bean class="com.x.spring.test3.event.RainListener1"></bean>
<bean class="com.x.spring.test3.event.RainListener2"></bean>
</beans>
测试类:
public class EventTest {
public static void main(String[] args) {
// TODO Auto-generated method stub
//自定义事件
try {
String path = "com/x/spring/test3/event/event.xml";
ApplicationContext container =
new ClassPathXmlApplicationContext(path);
/*spring容器发布事件之后,容器中的所有监听器都会调用指定方法去处理*/
/*所以我们需要提前把监听器对象配置spring容器里面*/
container.publishEvent(new RainEvent("下雨了"));
} catch (Exception e) {
e.printStackTrace();
}
}
}
运行效果: