自定义事件
import org.springframework.context.ApplicationEvent;/** * @author Kevin * @description 自定义事件 * @date 2016/6/30 */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; }}
事件监听器
import org.springframework.context.ApplicationListener;import org.springframework.stereotype.Component;/** * @author Kevin * @description 事件监听器 * @date 2016/6/30 */@Componentpublic class DemoListener implements ApplicationListener{ @Override public void onApplicationEvent(DemoEvent demoEvent) { String msg = demoEvent.getMsg(); System.out.println("DemoListener接收到了DemoPublisher发布的消息:" + msg); }}
事件发布类
import org.springframework.beans.factory.annotation.Autowired;import org.springframework.context.ApplicationContext;import org.springframework.stereotype.Component;/** * @author Kevin * @description 事件发布类 * @date 2016/6/30 */@Componentpublic class DemoPublisher { // 注入applicationContext用来发布事件 @Autowired ApplicationContext applicationContext; // 发布事件 public void publish(String msg) { applicationContext.publishEvent(new DemoEvent(this, msg)); }}
配置类
import org.springframework.context.annotation.ComponentScan;import org.springframework.context.annotation.Configuration;/** * @author Kevin * @description 配置类 * @date 2016/6/30 */@Configuration@ComponentScan("ch02.event")public class EventConfig {}
运行
import org.springframework.context.annotation.AnnotationConfigApplicationContext;/** * @author Kevin * @description * @date 2016/6/30 */public class Main { public static void main(String[] args) { AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(EventConfig.class); DemoPublisher demoPublisher = context.getBean(DemoPublisher.class); demoPublisher.publish("this is a application event"); context.close(); }}
结果
事件监听类将得到输出信息