发送事件
public class DemoEvent extends ApplicationEvent {
@Getter
private UserInfo userInfo;
public DemoEvent(UserInfo source) {
super(source);
userInfo = source;
}
}
@RestController
@RequestMapping(path = {"/api/hz/demoEvent"})
public class DemoEventController {
@RequestMapping(path = "/event", method = {RequestMethod.POST,RequestMethod.GET}, produces = "application/json;charset=UTF-8")
public Response demo(){
UserInfo info = new UserInfo();
info.setName("dage");
DemoEvent demoEvent = new DemoEvent(info);
SpringContextHelper.getApplicationContext().publishEvent(demoEvent);
return Response.OK;
}
}
监听事件
@Component
public class DemoEventListener implements ApplicationListener<DemoEvent> {
@Override
public void onApplicationEvent(DemoEvent demoEvent) {
UserInfo userInfo = demoEvent.getUserInfo();
System.out.println(userInfo.getName());
}
}

本文介绍了如何在Spring Boot应用中创建自定义事件`DemoEvent`,通过`@RestController`实现事件发布,并通过`@Component`监听器处理事件。重点展示了`DemoEventListener`如何捕获并操作`DemoEvent`中的`UserInfo`对象。
1994

被折叠的 条评论
为什么被折叠?



