public class DemoEvent extends ApplicationEvent {
private String eventName;
public DemoEvent(Object source,String eventName) {
super(source);
this.eventName=eventName;
}
public String getEventName() {
return eventName;
}
public void setEventName(String eventName) {
this.eventName = eventName;
}
@Override
public String toString() {
return "DemoEvent{" +
"eventName='" + eventName + '\'' +
", source=" + source +
'}';
}
}
-
新建事件监听器:DemoListener,放入到spring IOC容器中(如果不写DemoEvent泛型可以监听spring boot发出的事件)
@Component
public class DemoListener implements ApplicationListener<DemoEvent> {
public void onApplicationEvent(DemoEvent event) {
System.out.println("DemoListener捕获到事件: "+event);
}
}
-
触发事件:使用ApplicationRunner,当spring boot启动成功后触发自定义事件DemoEvent
@Component
public class DemoApplicationRunner implements ApplicationRunner {
@Autowired
private ApplicationEventPublisher applicationEventPublisher;
public void run(ApplicationArguments args) throws Exception {
System.out.println("spring boot启动成功后发送demo事件");
DemoEvent demoEvent=new DemoEvent(this,"spring boot启动成功");
applicationEventPublisher.publishEvent(demoEvent);
}
}
@SpringBootApplication
public class Demo2App {
public static void main(String[] args) {
SpringApplication.run(Demo2App.class,args);
}
}