- 第一步需要有一个事件对象
public class MyCustomEvent extends ApplicationEvent {
private String msg;
public MyCustomEvent(Object source) {
super(source);
}
public MyCustomEvent(Object source,String msg){
super(source);
this.msg = msg;
}
public String getMsg() {
return msg;
}
public void setMsg(String msg) {
this.msg = msg;
}
}
- 第二步需要监听事件的监听器,一发生该事件就触发操作。
@Component
public class MyListener implements ApplicationListener<MyCustomEvent> {// 范型是监听的事件
@Override
public void onApplicationEvent(MyCustomEvent event) {
System.out.println("我监听到该事件:" +event.getMsg());
}
}
- 发布事件
@Component
public class MyRunner implements CommandLineRunner { //实现这个接口,该类会在spring容器启动之后执行run()方法
@Autowired
private MyPublisher myPublisher;
@Override
public void run(String... args) throws Exception {
myPublisher.publish("hello world");
}
}
- 输出
我监听到该事件:hello world
- 关于事件的补充
事件的顶层父类是ApplicationEvent
等等。