1

定义事件

@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 = [测试事件监听]"

代码: async


lijingyulee
91 声望7 粉丝