其他分享
首页 > 其他分享> > springboot监听器

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 "下单成功";
    }
}

 

标签:MsgEvent,springboot,class,aware,source,监听器,public,String
来源: https://www.cnblogs.com/qiaojavaxiaobai/p/16484598.html