6. Spring4.x 事件 ApplicationEvent

weixin_33866037發表於2017-08-29

ApplicationEvent的基本使用

  1. 自定義事件
package com.xiaohan.event;

import org.springframework.context.ApplicationEvent;

public class DemoEvent extends ApplicationEvent{

    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;
    }
}
  1. 事件監聽器
package com.xiaohan.event;

import org.springframework.context.ApplicationListener;
import org.springframework.stereotype.Component;

//指定監聽的事件型別
@Component
public class DemoListener implements ApplicationListener<DemoEvent> {

    // 接收訊息 並處理訊息
    @Override
    public void onApplicationEvent(DemoEvent demoEvent) {
        String msg = demoEvent.getMsg();
        System.err.println(this.getClass().getName() + "監聽到了" + demoEvent.getSource().getClass().getName() + "的訊息: " + msg);
    }
}
  1. 事件釋出類
package com.xiaohan.event;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Component;

@Component
public class DemoPublisher {

    // 注入Spring容器
    @Autowired
    private ApplicationContext ac;

    public void publish(String msg) {
        ac.publishEvent(new DemoEvent(this, msg));
    }
}
  1. 配置類
package com.xiaohan.event;

import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;

@Configuration
@ComponentScan("com.xiaohan.event")
public class EventConfig {
}
  1. Main測試類
package com.xiaohan.event;

import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;

// 事件   ApplicationEvent
public class Main {
    public static void main(String[] args) {
        ApplicationContext ac = new AnnotationConfigApplicationContext(EventConfig.class);
        DemoPublisher demoPublisher = ac.getBean(DemoPublisher.class);
        demoPublisher.publish("hello application event");
    }
}

輸出

com.xiaohan.event.DemoListener監聽到了com.xiaohan.event.DemoPublisher的訊息: hello application event

相關文章