SpringBoot事件监听的4种实现方式
java1234
共 3185字,需浏览 7分钟
·
2022-01-06 18:37
点击上方蓝色字体,选择“标星公众号”
优质文章,第一时间送达
springboot进行事件监听有四种方式:
1.手工向ApplicationContext中添加监听器
2.将监听器装载入spring容器
3.在application.properties中配置监听器
4.通过@EventListener注解实现事件监听
讲到事件监听,这里我们说下自定义事件和自定义监听器类的实现方式:
自定义事件:继承自ApplicationEvent抽象类,然后定义自己的构造器
自定义监听:实现ApplicationListener
public class MyListener1 implements ApplicationListener
{
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
{
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
{
Logger logger = Logger.getLogger(MyListener3.class);
public void onApplicationEvent(MyEvent event)
{
logger.info(String.format("%s监听到事件源:%s.", MyListener3.class.getName(), event.getSource()));
}
}
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监听到事件源:测试事件..
作者:ignorewho
来源:csdn.net/ignorewho/article/details/80702827
评论