SpringBoot -- 事件(Application Event)

   Spring的事件爲Bean與Bean之間的消息通訊提供了支持,當一個Bean處理完一個任務以後,但願另一個Bean知道並能作相應的處理,這時咱們就須要讓一個Bean監聽當前Bean所發送的事件。spring

  Spring的事件須要遵循以下流程:app

  1. 自定義事件,集成ApplicationEvent。
  2. 定義事件監聽器,實現ApplicationListener。
  3. 使用容器發佈事件。

1、自定義事件ide

package com.cenobitor.appevent.event;

import org.springframework.context.ApplicationEvent;

public class DemoEvent extends ApplicationEvent {

    private static final long serialVersionUID = 1L;
    private String msg;

    public DemoEvent(Object source,String msg) {
        super(source);
        this.msg = msg;
    }

    public String getMsg() {
        return msg;
    }

    public void setMsg(String msg) {
        this.msg = msg;
    }
}

2、事件監聽器this

package com.cenobitor.appevent.listener;

import com.cenobitor.appevent.event.DemoEvent;
import org.springframework.context.ApplicationListener;
import org.springframework.stereotype.Component;

//實現ApplicationListener接口,並指定監聽的事件類型 @Component
public class DemoListener implements ApplicationListener<DemoEvent> { @Override
  //使用onApplicationEvent方法對消息進行接收處理
public void onApplicationEvent(DemoEvent demoEvent) { String msg = demoEvent.getMsg(); System.out.println("(bean-demoListener)接收到了bean-demoPublisher發佈的消息:"+msg); } }

3、事件發佈類spa

package com.cenobitor.appevent.publisher;

import com.cenobitor.appevent.event.DemoEvent;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Component;

@Component
public class DemoPublisher {
    @Autowired
  //注入ApplicationContext用來發布事件 ApplicationContext applicationContext;   //使用ApplicationContext的publishEvent方法來發布
public void publish(String msg){ applicationContext.publishEvent(new DemoEvent(this,msg)); } }

4、運行code

package com.cenobitor.appevent;

import com.cenobitor.appevent.publisher.DemoPublisher;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;

public class Main {
    public static void main(String[] args) {
        AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(AppeventApplication.class);
        DemoPublisher demoPublisher = context.getBean(DemoPublisher.class);
        demoPublisher.publish("hello application event");
        context.close();
    }

}

結果:(bean-demoListener)接收到了bean-demoPublisher發佈的消息:hello application eventblog

 注:摘抄自《JavaEE開發的顛覆者SpringBoot 實戰》。接口

相關文章
相關標籤/搜索