天天看點

精通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