共计 785 个字符,预计需要花费 2 分钟才能阅读完成。
定义事件
@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);
}
}
测试时执行顺序:
i 循环
打印 ”event = [测试事件监听]”
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() + “]”);
}
}
}
测试时执行顺序:
i 循环
j 循环
打印 ”event = [测试事件监听]”
代码:async