springboot框架提供了監聽的方法 具體實現看下面代碼,
首先創建一個被監聽的類, 繼承ApplicationEvent 抽象類, 要實現一個有參的構造方法
public class TestEvent extends ApplicationEvent {
public TestEvent(Object source) {
super(source);
System.out.println("這是一個事件的構造!!!!!繼承了ApplicationEvent類");
}
}
接下來再寫一個監聽類,用來監聽上面的類
@Component
public class TestListener {
@Async
@EventListener(TestEvent.class)
public void listener(TestEvent testEvent){
System.out.println("這是一個監聽類,監聽對應的事件,監聽TestEvent.class 該類須繼承 ApplicationEvent ");
}
}
自己定義一個方法 添加@EventListener(TestEvent.class) 註解, 註解中的TestEvent.class 是指定要監聽的類,@Async 這個註解是爲了讓這個監聽方法是異步執行的.
接下來是監聽的調用
@Controller
@RequestMapping("/listener")
public class TestListenerController {
@Autowired
private ApplicationEventPublisher publisher;
@GetMapping("/test1")
public void test1(){
System.out.println("請求監聽:");
/*調用被監聽的方法*/
publisher.publishEvent( new TestEvent("323232"));
System.out.println("該輸出在請求方法最後");
}
}
當調用被監聽類中方法的時候首先 要注入ApplicationEventPublisher 類, 通過這個類調用 TestEvent 的有參構造,實例化,這時監聽類 TestListener類中的 listener 方法就會執行, 因爲加了@Async註解, 所以這個方法是異步執行的, 如果不加, 那就是同步的, 效果跟普通調用也差不多