1. 程式人生 > >Spring 的監聽事件 ApplicationListener 和 ApplicationEvent 用法

Spring 的監聽事件 ApplicationListener 和 ApplicationEvent 用法

scan bsp string bject wired static final HA AD

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
  *
 */
@Component
public 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
  *
 */
@Component
public 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 用法