This article brings you an introduction to springboot event monitoring (with code). It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.
Define events
@Getter public class TestEvent extends ApplicationEvent { private String msg; public TestEvent(Object source, String msg) { super(source); this.msg = msg; } }
Define event monitoring (annotation method)
@Component public class TestListen { @EventListener public void testListen(TestEvent event) { System.out.println(event.getMsg()); } }
Note: @Component annotation
Publish event
@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); } }
Execution sequence during testing:
Asynchronous monitoring
Listening plus @Async annotation
@Component public class TestListen { @EventListener @Async public void testListen(TestEvent event) { for (int i = 0; i < 10; i++) { System.out.println("event = [" + event.getMsg() + "]"); } } }
Execution order during testing:
The above is the detailed content of Introduction to springboot event monitoring (with code). For more information, please follow other related articles on the PHP Chinese website!