栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 前沿技术 > 大数据 > 大数据系统

【Spring Boot实战与进阶】自定义事件及监听,kafka面试题零拷贝

【Spring Boot实战与进阶】自定义事件及监听,kafka面试题零拷贝

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();

}

}

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/682998.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号