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


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM