Spring容器事件小实例

11 篇文章 0 订阅

这个实例,真的是非常小的实例~主要实现了时间发布和事件监听的过程。
比如在上学的时候,我们经常要到学校食堂吃饭,但是刚进来的新生不一定了解学校食堂开饭时间,就订阅了学校食堂的广播通知~~~那么实现代码来了。
先来定义一个事件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("食堂五分钟之后开饭啦!!!");

至此,这个食堂开饭广播器就完成了。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值