springboot监听器

首先创建类,定义一个事件,继承ApplicationEvent类实现方法

/**
* 定义一个事件
*/
public class MsgEvent extends ApplicationEvent {
public MsgEvent(Object source) {
super(source);
}
}

定义一个监听者,实现接口ApplicationListener,实现方法,传入MsgEvent这个事件

1 @Component
2 public class EmailListener implements ApplicationListener<MsgEvent> {
3     @Override
4     public void onApplicationEvent(MsgEvent event) {
5         String source = (String) event.getSource();
6         System.out.println(source + "已经收到您的订单");
7     }
8 }
Controller层实现ApplicationContextAware接口
复制代码
@RestController
public class UserController implements ApplicationContextAware {


    private ApplicationContext aware;

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.aware = applicationContext;
    }

    @GetMapping("/hello")
    public String api(){
        aware.publishEvent(new MsgEvent("下单了"));
        return "下单成功";
    }
}
复制代码

 

posted @   敲代码的空白格  阅读(639)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· Manus的开源复刻OpenManus初探
· AI 智能体引爆开源社区「GitHub 热点速览」
· 三行代码完成国际化适配,妙~啊~
· .NET Core 中如何实现缓存的预热?
点击右上角即可分享
微信分享提示