您现在的位置是:首页 > 文章详情

精通SpringBoot——第四篇:Spring事件 Application Event

日期:2018-07-21点击:395

Spring的事件为Bean与Bean之间的通信提供了支持,当我们系统中某个Spring管理的Bean处理完某件事后,希望让其他Bean收到通知并作出相应的处理,这时可以让其他Bean监听当前这个Bean所发送的事件。

要实现事件的监听,我们要做两件事:
1:自定义事件,继承ApplicationEvent接口
2:定义事件监听器,实现ApplicationListener
3:事件发布类


/**
 * @TODO // 自定义事件,继承ApplicationEvent接口
 * @Author Lensen
 * @Date 2018/7/22
 * @Description
 */
public class SendMsgEvent extends ApplicationEvent {

    private static final long serialVersionID = 1L;

    // 收件人
    public String receiver;

    // 收件内容
    public String content;

    public SendMsgEvent(Object source) {
        super(source);
    }

    public SendMsgEvent(Object source, String receiver, String content) {
        super(source);
        this.receiver = receiver;
        this.content = content;
    }

    public void output(){
        System.out.println("I had been sand a msg to " + this.receiver);
    }
}

/**
 * @TODO //定义事件监听器,实现ApplicationListener
 * @Author Lensen
 * @Date 2018/7/22
 * @Description
 */@Component
public class MsgListener implements ApplicationListener<SendMsgEvent> {
    @Override
    public void onApplicationEvent(SendMsgEvent sendMsgEvent) {
        sendMsgEvent.output();
        System.out.println(sendMsgEvent.receiver + "received msg : " + sendMsgEvent.content );
    }
}

事件发布类

@Component
public class Publisher {
    @Autowired
    ApplicationContext applicationContext;

    public void publish(Object source, String receiver, String content){
        applicationContext.publishEvent(new SendMsgEvent(source, receiver, content));
    }
}

测试消息:WebConfig.class主要是为了扫描Publisher 和Listener类。里面有两个注解@ComponenScan和@Configuration。

    public static void main(String[] args) {
        AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext(WebConfig.class);
        Publisher publisher = applicationContext.getBean(Publisher.class);
        publisher.publish("Hello,World!","Mr.Lensen", "I Love U");
    }

结果:

I had been sand a msg to Mr.Lensen
Mr.Lensen received msg : I Love U
原文链接:https://yq.aliyun.com/articles/617371
关注公众号

低调大师中文资讯倾力打造互联网数据资讯、行业资源、电子商务、移动互联网、网络营销平台。

持续更新报道IT业界、互联网、市场资讯、驱动更新,是最及时权威的产业资讯及硬件资讯报道平台。

转载内容版权归作者及来源网站所有,本站原创内容转载请注明来源。

文章评论

共有0条评论来说两句吧...

文章二维码

扫描即可查看该文章

点击排行

推荐阅读

最新文章