1. 程式人生 > >Springboot-Listener(springboot的事件監聽的4種實現方式)

Springboot-Listener(springboot的事件監聽的4種實現方式)

prope nds ack nis stat fff span 文件中 out

springboot事件監聽的4種方式

第1種:

1.自定義事件MyApplicationEvent繼承ApplicationEvent

import org.springframework.context.ApplicationEvent;

/**
* Created by Administrator on 2018\11\13 0013.
* 自定義事件繼承ApplicationEvent
*/
public class MyApplicationEvent extends ApplicationEvent {
public MyApplicationEvent(Object source) {

super(source);
}
}

2.定義一個事件監聽器MyApplicationListener實現ApplicationListener接口

public class MyApplicationListener implements ApplicationListener<MyApplicationEvent>{
@Override
public void onApplicationEvent(MyApplicationEvent event) {
System.out.println("接收到事件:"+event.getClass());
}
}

3.測試運行

@SpringBootApplication
public class ApplicationDemo {
public static void main(String[] args) {
//創建一個可執行的spring應用程序
SpringApplication application = new SpringApplication(ApplicationDemo.class);
//配置事件監聽器
application.addListeners(new MyApplicationListener());
//配置應用程序上下文
ConfigurableApplicationContext context =application.run(args);
//發布事件
context.publishEvent(new MyApplicationEvent(new Object()));
//關閉監視器
context.close();
}

}

技術分享圖片

第2種:

在第1種的基礎上直接在MyApplicationListener類上加上@Component註解,納入spring容器管理

@SpringBootApplication
public class ApplicationDemo {
public static void main(String[] args) {
//創建一個可執行的spring應用程序
SpringApplication application = new SpringApplication(ApplicationDemo.class);
//配置事件監聽器
//application.addListeners(new MyApplicationListener());
//配置應用程序上下文
ConfigurableApplicationContext context =application.run(args);
//發布事件
context.publishEvent(new MyApplicationEvent(new Object()));
//關閉監視器
context.close();
}

}

技術分享圖片


第3種:

在application.properties配置文件中配置context.listener.classes=您的包路徑.MyApplicationListener

DelegatingApplicationListener 委派監聽器 對配置文件進行解析,得到監聽器集合,註入Spring容器

技術分享圖片

第4種:

使用@EventListener註解

@Component
public class MyEventHandle {
/**
* 參數任意(為Object)的時候所有事件都會監聽到
* 所有,該參數事件,或者其子事件(子類)都可以接收到
*/
@EventListener
public void event(Object event){
System.out.println("MyEventHandle 接收到事件:" + event.getClass());
}

}

技術分享圖片

Springboot-Listener(springboot的事件監聽的4種實現方式)