Springboot之监听器的使用
在业务开发中经常会用到监听器,例如在多个场景触发同一类型的事件,这个时候就比较适合使用监听器,那么在Spring-boot中使用监听器有几种形式,这几种形式稍微有点区别
自定义SpringApplication的启动
SpringApplication springApplication = new SpringApplication(Application.class); springApplication.addListeners(new ApplicationListenerTest());
springApplication.run(args);
在META-INF/spring.factories中自定义
org.springframework.context.ApplicationListener= com.dragon.myapplication.mylistener.ApplicationListenerTest
使用@Component注解来注入
@Componentpublic class ApplicationListenerTest implements ApplicationListener<ApplicationEvent> {
public void onApplicationEvent(ApplicationEvent applicationEvent) {
if(applicationEvent instanceof ApplicationStartingEvent){
System.out.println("事件超类:ApplicationStartingEvent:"+ JSON.toJSONString(applicationEvent));
}
if(applicationEvent instanceof ApplicationEnvironmentPreparedEvent){
System.out.println("事件超类:ApplicationEnvironmentPreparedEvent:"+ JSON.toJSONString(applicationEvent));
}
if(applicationEvent instanceof ApplicationContextInitializedEvent){
ApplicationContextInitializedEvent event = (ApplicationContextInitializedEvent)applicationEvent;
System.out.println("事件超类:ApplicationContextInitializedEvent"+event.getApplicationContext());
}
if(applicationEvent instanceof ApplicationPreparedEvent){
ApplicationPreparedEvent event = (ApplicationPreparedEvent)applicationEvent;
System.out.println("事件超类:ApplicationPreparedEvent"+event.getApplicationContext());
}
if(applicationEvent instanceof ApplicationStartedEvent){
ApplicationStartedEvent event = (ApplicationStartedEvent)applicationEvent;
event.getApplicationContext().publishEvent(new MyApplicationEvent(event.getSource(),new Order()));
System.out.println("事件超类:ApplicationStartedEvent"+event.getApplicationContext());
}
if(applicationEvent instanceof ApplicationReadyEvent){
ApplicationReadyEvent event = (ApplicationReadyEvent)applicationEvent;
System.out.println("事件超类:ApplicationReadyEvent"+event.getApplicationContext());
}
if(applicationEvent instanceof ApplicationFailedEvent){
ApplicationFailedEvent event = (ApplicationFailedEvent)applicationEvent;
System.out.println("事件超类:ApplicationFailedEvent"+event.getApplicationContext());
}
}
}
使用其他的方式,例如通过@Bean来
这几种的方式的区别在哪里,主要是在对于事件监听的结果上面,一般业务开发中只会关心自定义的事件,那么推荐使用@Component方式,如果对spring-boot的框架事件比较感兴趣的话,需要时候用前两种,因为如果使用注解的方式的话,有些在容器没有启动的时候,事件本省已经发出了,导致获取不到事情,还有一点就是如果获取到框架的事件,那么从事件中就能获取到容器,即然能够获取到容器了,那么想干嘛就干嘛
以上是 Springboot之监听器的使用 的全部内容, 来源链接: utcz.com/z/514850.html