[SpringBoot] Spring的事件機制
阿新 • • 發佈:2018-12-28
直接上程式碼:
一.定義事件
public class MyEvent extends ApplicationEvent {
private String msg;
public MyEvent(Object source, String msg) {
super(source);
this.msg = msg;
}
public String getMsg() { return msg; }
}
PS:繼承ApplicationEvent
二.定義監聽者
@Component public class MyListener implements ApplicationListener<MyEvent> { @Override public void onApplicationEvent(MyEvent myEvent) { //監聽後的邏輯,這裡簡單列印 String msg = myEvent.getMsg(); System.out.println("MyListener接收到了MyPublisher釋出的訊息:" + msg); } } PS:實現ApplicationListener介面,指定事件型別
三.定義釋出者
@Component public class MyPublisher { @Autowired ApplicationContext context; public void published() { MyEvent event = new MyEvent(this, "釋出成功!"); System.out.println("釋出event:" + event); context.publishEvent(event); } } PS:注入ApplicationContext ,通過ApplicationContext的publisEvent方法釋出事件;
四.釋出測試
@SpringBootApplication
@RestController
public class SpringDefineConfigApplication {
@Autowired
MyPublisher myPublisher;
public static void main(String[] args) {
ApplicationContext applicationContext =
SpringApplication.run(SpringDefineConfigApplication.class, args);
}
@GetMapping("/publish")
public void publish(){
myPublisher.published();
}
}
PS:注入事件釋出者,只掉呼叫方法即可釋出事件
訪問/publish介面即可看到列印如下:
釋出event:com.intellif.mozping.event.MyEvent[ [email protected]]
MyListener接收到了MyPublisher釋出的訊息:釋出成功!