springboot 事件监听的介绍(附代码)

springboot 事件监听的介绍(附代码),第1张

springboot 事件监听的介绍(附代码)

本篇文章给大家带来的内容是关于springboot 事件监听的介绍(附代码),有一定的参考价值,有需要的朋友可以参考一下,希望对你有所帮助。

定义事件

@Getter
public class TestEvent extends ApplicationEvent {
   private String msg;

   public TestEvent(Object source, String msg) {
       super(source);
       this.msg = msg;
   }
}

定义事件监听(注解方式)

 @Component
 public class TestListen {
   @EventListener
   public void testListen(TestEvent event) {
       System.out.println(event.getMsg());
   }
}

注意:@Component 注解

发布事件

@Autowired
private ApplicationContext publiser;

@GetMapping("test-listen")
public void testListen() {
    for (int i = 0; i < 10; i++) {
        System.out.println("i = " + i);
    }
    publiser.publishEvent(new TestEvent(this, "测试事件监听"));
    for (int j = 0; j < 10; j++) {
       System.out.println("j = " + j);
   }
}

测试时执行顺序:

  1. i循环
  2. 打印"event = [测试事件监听]"
  3. j循环

异步监听

监听加上@Async注解

@Component
public class TestListen {
   @EventListener
   @Async
   public void testListen(TestEvent event) {
       for (int i = 0; i < 10; i++) {
           System.out.println("event = [" + event.getMsg() + "]");
       }
   }
}

测试时执行顺序:

  1. i循环
  2. j循环
  3. 打印"event = [测试事件监听]"

以上就是springboot 事件监听的介绍(附代码)的详细内容,

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/langs/687281.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-04-21
下一篇 2022-04-21

发表评论

登录后才能评论

评论列表(0条)

保存