1、引导类
package com.imooc.springapplication;
import org.springframework.context.ApplicationEvent;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
public class SpringApplicationEventBootstrap {
public static void main(String[] args) {
//创建上下文
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext();
//注册应用事件监听器
context.addApplicationListener(event -> {
System.out.println("监听到事件:" + event);
});
//启动上下文
context.refresh();
//发送事件
context.publishEvent("HelloWorld");
context.publishEvent("2018");
context.publishEvent(new ApplicationEvent("小马哥"){
});
//关闭上下文
context.close();
}
}
2、运行结果
监听到事件:org.springframework.context.event.ContextRefreshedEvent[source=org.springframework.context.annotation.AnnotationConfigApplicationContext@515f550a, started on Tue Jan 08 22:51:49 CST 2019]
监听到事件:org.springframework.context.PayloadApplicationEvent[source=org.springframework.context.annotation.AnnotationConfigApplicationContext@515f550a, started on Tue Jan 08 22:51:49 CST 2019]
监听到事件:org.springframework.context.PayloadApplicationEvent[source=org.springframework.context.annotation.AnnotationConfigApplicationContext@515f550a, started on Tue Jan 08 22:51:49 CST 2019]
监听到事件:com.imooc.springapplication.SpringApplicationEventBootstrap$1[source=小马哥]
22:51:49.462 [main] DEBUG org.springframework.context.annotation.AnnotationConfigApplicationContext - Closing org.springframework.context.annotation.AnnotationConfigApplicationContext@515f550a, started on Tue Jan 08 22:51:49 CST 2019
监听到事件:org.springframework.context.event.ContextClosedEvent[source=org.springframework.context.annotation.AnnotationConfigApplicationContext@515f550a, started on Tue Jan 08 22:51:49 CST 2019]