原创

精通Spring Boot教程(04):Spring 事件 Application Event

1.引言

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

2.事件监听

要实现事件的监听,我们要做两件事:
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));
    }
}

3.测试

测试消息: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

4.总结

实现Spring事件监听,我们只需要自己自定义事件,继承ApplicationEvent接口,然后定义事件监听器,实现ApplicationListener,这样就可以完成一个简单的监听事件了!

正文到此结束