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

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
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值