定义事件
@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
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。