SpringBoot事件监听
SpringBoot事件监听
springBoot事件监听流程
1 自定义事件,一般是继承ApplicationEvent抽象类
/** * 定义事件 **/ public class MyApplicationEvent extends ApplicationEvent { private static final long serialVersionUID = 787751246882182041L; public MyApplicationEvent(Object source) { super(source); } }
2 自定义监听器,一般是实现ApplicationListen接口
/** * 自定义监听器 **/ @Component public class MyApplicationListener implements ApplicationListener<MyApplicationEvent>{ @Override public void onApplicationEvent(MyApplicationEvent event) { System.out.println("接收事件:"+event.getClass()); } }
3 发布事件
@SpringBootApplication(exclude = {DataSourceAutoConfiguration.class, HibernateJpaAutoConfiguration.class}) public class App { public static void main(String[] args) { ConfigurableApplicationContext context = SpringApplication.run(App.class, args); //发布事件 context.publishEvent(new MyApplicationEvent(new Object())); context.close(); } }
这就是SpringBoot中最简单的一个事件监听.