SpringBoot事件监听的4种实现方式
程序员的成长之路
共 3414字,需浏览 7分钟
·
2021-12-18 16:17
阅读本文大概需要 2.8 分钟。
来自:blog.csdn.net/ignorewho/article/details/80702827
手工向ApplicationContext中添加监听器 将监听器装载入spring容器 在application.properties中配置监听器 通过@EventListener注解实现事件监听
自定义事件:继承自ApplicationEvent抽象类,然后定义自己的构造器 自定义监听:实现 ApplicationListener
接口,然后实现onApplicationEvent方法
方式1
public class MyListener1 implements ApplicationListener<MyEvent>
{
Logger logger = Logger.getLogger(MyListener1.class);
public void onApplicationEvent(MyEvent event)
{
logger.info(String.format("%s监听到事件源:%s.", MyListener1.class.getName(), event.getSource()));
}
}
@SpringBootApplication
public class LisenterApplication
{
public static void main(String[] args)
{
ConfigurableApplicationContext context = SpringApplication.run(LisenterApplication.class, args);
//装载监听
context.addApplicationListener(new MyListener1());
}
}
方式2
@Component
public class MyListener2 implements ApplicationListener<MyEvent>
{
Logger logger = Logger.getLogger(MyListener2.class);
public void onApplicationEvent(MyEvent event)
{
logger.info(String.format("%s监听到事件源:%s.", MyListener2.class.getName(), event.getSource()));
}
}
方式3
public class MyListener3 implements ApplicationListener<MyEvent>
{
Logger logger = Logger.getLogger(MyListener3.class);
public void onApplicationEvent(MyEvent event)
{
logger.info(String.format("%s监听到事件源:%s.", MyListener3.class.getName(), event.getSource()));
}
}
application.properties
中配置监听context.listener.classes=com.listener.MyListener3
方式4
@Component
public class MyListener4
{
Logger logger = Logger.getLogger(MyListener4.class);
@EventListener
public void listener(MyEvent event)
{
logger.info(String.format("%s监听到事件源:%s.", MyListener4.class.getName(), event.getSource()));
}
}
@SuppressWarnings("serial")
public class MyEvent extends ApplicationEvent
{
public MyEvent(Object source)
{
super(source);
}
}
@SpringBootApplication
public class LisenterApplication
{
public static void main(String[] args)
{
ConfigurableApplicationContext context = SpringApplication.run(LisenterApplication.class, args);
//装载事件
context.addApplicationListener(new MyListener1());
//发布事件
context.publishEvent(new MyEvent("测试事件."));
}
}
2018-06-15 10:51:20.198 INFO 4628 --- [ main] com.listener.MyListener3 : com.listener.MyListener3监听到事件源:测试事件..
2018-06-15 10:51:20.198 INFO 4628 --- [ main] com.listener.MyListener4 : com.listener.MyListener4监听到事件源:测试事件..
2018-06-15 10:51:20.199 INFO 4628 --- [ main] com.listener.MyListener2 : com.listener.MyListener2监听到事件源:测试事件..
2018-06-15 10:51:20.199 INFO 4628 --- [ main] com.listener.MyListener1 : com.listener.MyListener1监听到事件源:测试事件..
https://github.com/ingorewho/springboot-develope/tree/master/springboot-listener
终于实现了 SpringBoot+WebSocket实时监控异常....
内容包含Java基础、JavaWeb、MySQL性能优化、JVM、锁、百万并发、消息队列、高性能缓存、反射、Spring全家桶原理、微服务、Zookeeper、数据结构、限流熔断降级......等技术栈!
⬇戳阅读原文领取! 朕已阅
评论