2、自定义事件,继承
SpringApplicationEvent 重写 CustomizingEvent
public class CustomizingEvent extends SpringApplicationEvent {
public CustomizingEvent(SpringApplication application, String[] args) {
super(application, args);
System.out.println("............CustomizingEvent............");
}
}
3、自定义监听器 实现
ApplicationListener 中的 onApplicationEvent方法
public class CustomizingEventListener implements ApplicationListener<CustomizingEvent> {
@Override
public void onApplicationEvent(CustomizingEvent event) {
System.out.println("........................CustomizingEventListener........................");
}
}
4、模拟事件发生
@SpringBootApplication
public class EventsAndListenersApplication {
public static void main(String[] args) {
SpringApplication application = new SpringApplication(EventsAndListenersApplication.class);
ApplicationStartingEventListener applicationStartingListenerCustomizing = new ApplicationStartingEventListener();
//注册监听器
application.addListeners(new CustomizingEventListener());
ConfigurableApplicationContext context = application.run(args);
//发布事件
context.publishEvent(new CustomizingEvent(application, args));
}
}
5、运行看结果