这个实例,真的是非常小的实例~主要实现了时间发布和事件监听的过程。
比如在上学的时候,我们经常要到学校食堂吃饭,但是刚进来的新生不一定了解学校食堂开饭时间,就订阅了学校食堂的广播通知~~~那么实现代码来了。
先来定义一个事件RestaurantEvent
public class RestaurantEvent extends ApplicationContextEvent {
private String msg;
public RestaurantEvent(ApplicationContext source, String msg) {
super(source);
this.msg = msg;
}
public String getMsg() {
return msg;
}
}
再来实现一个事件监听器RestaurantListener,负责监听RestaurantEvent 事件
public class RestaurantListener implements ApplicationListener<RestaurantEvent> {
public void onApplicationEvent(RestaurantEvent event) {
RestaurantEvent mse = event;
System.out.println("RestaurantListener:" + mse.getMsg());
}
}
接下来就是实现一个事件广播器,发布事件
public class Restaurant implements ApplicationContextAware {
private ApplicationContext ctx;
// 容器启动时注入容器实例
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
this.ctx = applicationContext;
}
public void sendMail(String to) {
System.out.println("模拟开饭了...");
RestaurantEvent mse = new RestaurantEvent(ctx, to);
// 向容器中的所有事件监听器发送事件
ctx.publishEvent(mse);
}
}
好了。三步骤,这里差不多就完成了,最后还需要在Spring配置文件中定义Bean
<bean class="com.smart.event.RestaurantListener" />
<bean id="restaurant" class="com.smart.event.Restaurant" />
一切准备就绪之后,只需要启动启动Spring容器,就能达到我们所需的目的了。
ApplicationContext ctx = new ClassPathXmlApplicationContext("com/smart/event/beans.xml");
Restaurant restaurant = (Restaurant) ctx.getBean("restaurant");
restaurant.sendMail("食堂五分钟之后开饭啦!!!");
至此,这个食堂开饭广播器就完成了。