标签:事件监听器 ring 程序 事件监听 obj undefined getc 子类 nap
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();
}
}
在第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();
}
}
在application.properties配置文件中配置context.listener.classes=您的包路径.MyApplicationListener
DelegatingApplicationListener 委派监听器 对配置文件进行解析,得到监听器集合,注入Spring容器
使用@EventListener注解
@Component
public class MyEventHandle {
/**
* 参数任意(为Object)的时候所有事件都会监听到
* 所有,该参数事件,或者其子事件(子类)都可以接收到
*/
@EventListener
public void event(Object event){
System.out.println("MyEventHandle 接收到事件:" + event.getClass());
}
}
Springboot-Listener(springboot的事件监听的4种实现方式)
标签:事件监听器 ring 程序 事件监听 obj undefined getc 子类 nap
原文地址:https://www.cnblogs.com/h-java/p/9951547.html