Spring 的監聽事件 ApplicationListener 和 ApplicationEvent 用法

來源:互聯網
上載者:User

標籤:一個   syslog   event   extend   流程   class   nap   監聽   conf   

spring事件(application event)為Bean與Bean之間的訊息通訊添加了支援,當一個Bean處理完一個任務之後,希望另一個Bean知道並能做相應的處理,這時我們就需要另外一個Bean監聽當前Bean所發送的事件。
spring的事件需要遵循以下流程:
(1)自訂事件:繼承ApplicationEvent
(2)定義事件監聽器:實現ApplicationListener
(3)使用容器發布事件
下面是demo
事件類別

/*** *   * @ClassName(類名)      : DemoEvent(自訂事件)  * @Description(描述)    : spring的event為bean和bean之間的訊息通訊提供了支援,可以用一個bean監聽當前的bean所發送的事件  * @author(作者)         :吳桂鎮  * @date (開發日期)      :2017年11月22日 下午3:30:04  * */public class DemoEvent extends ApplicationEvent{    private static final long serialVersionUID = 1L;    private String msg;    public void sysLog() {        System.out.println(msg);    }    public DemoEvent(Object source,String msg) {        super(source);        this.setMsg(msg);    }    public String getMsg() {        return msg;    }    public void setMsg(String msg) {        this.msg = msg;    }}

監聽類

/*** *   * @ClassName(類名)      : demoListener  * @Description(描述)    : 事件監聽器  *                     實現ApplicationListener並制定監聽的事件類型  * @author(作者)         :吳桂鎮  * @date (開發日期)      :2017年11月22日 下午3:35:37  * */@Componentpublic class demoListener implements ApplicationListener<DemoEvent>{    /***     * 對訊息進行接受處理     */    @Override    public void onApplicationEvent(DemoEvent event) {        String msg = event.getMsg();        System.out.println("demoListener接受到了demoPublisher發布的訊息:"+msg);    }}

發布類

/*** *   * @ClassName(類名)      : DemoPublisher  * @Description(描述)    : 事件發布類  * @author(作者)         :吳桂鎮  * @date (開發日期)      :2017年11月22日 下午3:41:13  * */@Componentpublic class DemoPublisher {    @Autowired    ApplicationContext context;    public void published() {        DemoEvent event = new DemoEvent(this, "發布成功!");        System.out.println("發部event:"+event);        context.publishEvent(event);    }}

 

測試類別

@Configuration@ComponentScan({"com.wugz.app"})public class EventConfig {    public static void main(String[] args) {        AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(EventConfig.class);        DemoPublisher publisher = context.getBean(DemoPublisher.class);        publisher.published();        context.close();    }}

Spring 的監聽事件 ApplicationListener 和 ApplicationEvent 用法

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.