public void onApplicationEvent(MyApplicationEvent event) {
System.out.println(“接受到了事件:”+event.getClass());
System.out.println(“接受到了事件:”+event.getSource());
}
}
3、使用容器中发布事件
@SpringBootApplication
public class EventDemoApplication {
public static void main(String[] args) {
SpringApplication app = new SpringApplication(EventDemoApplication.class);
//1 添加监听事件
app.addListeners(new MyApplicationListener());
ConfigurableApplicationContext context = app.run(args);
// 发布事件
context.publishEvent(new MyApplicationEvent(new Object()));
context.close();
}
}
控制台输出:
接受到了事件:class com.boot.event.eventdemo.MyApplicationEvent
接受到了事件:java.lang.Object@f713686
1、自定义事件
public class MyApplicationEvent extends ApplicationEvent {
public MyApplicationEvent(Object source) {
super(source);
}
}
2、@EventListener注解的方式监听
@Component
public class HandlerEvent {
@EventListener(MyApplicationEvent.class)
public void handlerEvent(MyApplicationEvent event) {
System.out.println(“接受到了事件====:”+event.ge
《一线大厂Java面试题解析+后端开发学习笔记+最新架构讲解视频+实战项目源码讲义》
【docs.qq.com/doc/DSmxTbFJ1cmN1R2dB】 完整内容开源分享
tClass());
System.out.println(“接受到了事件====:”+event.getSource());
}
}
3、使用容器中发布事件
@SpringBootApplication
public class EventDemoApplication {
public static void main(String[] args) {
SpringApplication app = new SpringApplication(EventDemoApplication.class);
ConfigurableApplicationContext context = app.run(args);
// 发布事件
context.publishEvent(new MyApplicationEvent(new Object()));
context.close();
}
}
控制台输出:
接受到了事件====:class com.boot.event.eventdemo.MyApplicationEvent
接受到了事件====:java.lang.Object@352c308
1、自定义事件
public class MyApplicationEvent extends ApplicationEvent {
public MyApplicationEvent(Object source) {
super(source);
}
}
2、定义事件监听器
public class MyApplicationListener implements ApplicationListener {
@Override
public void onApplicationEvent(MyApplicationEvent event) {
System.out.println(“接受到了事件:”+event.getClass());
System.out.println(“接受到了事件:”+event.getSource());
}
}
3、使用容器中发布事件
@SpringBootApplication
public class EventDemoApplication {
public static void main(String[] args) {
SpringApplication app = new SpringApplication(EventDemoApplication.class);
ConfigurableApplicationContext context = app.run(args);
// 发布事件
context.publishEvent(new MyApplicationEvent(new Object()));
context.close();
}
}