@EventListener简单描述
简化我们编写监听类的步骤,不需要再继承ApplicationListener接口去实现onApplicationEvent了。
示例:
Event
@Data
public class CustomEvent {
private String title;
private String message;
public CustomEvent(String title, String message) {
this.title = title;
this.message = message;
}
}
Listener
@Component
public class CustomEventListener {
@EventListener(CustomEvent.class)
public void onApplicationEvent(CustomEvent customEvent){
System.out.println("监听器接受消息:"+System.currentTimeMillis());
System.out.println("标题title:" + customEvent.getTitle() + "接收到的消息为:"+customEvent.getMessage());
}
}
Controller调用
@RestController
@RequestMapping("/pro/test")
public class TestController {
@Resource
private ApplicationContext applicationContext;
@RequestMapping("/hello")
public String hello(){
System.out.println("事件开始发布消息:"+System.currentTimeMillis());
applicationContext.publishEvent(new CustomEvent("内容","你好啊"));
return "success";
}
}
结果:
事件开始发布消息:1644807739625
监听器接受消息:1644807739626
标题title:内容接收到的消息为:你好啊