Spring 监听器的简单用法

SpringApplicationListener用法与原理

SpringApplicationListener的简介与基本用法

SpringApplicationListener是Spring为我们提供的事件监听器,它主要是为我们提供事件监听机制,我们可以创建一个监听器,并向该监听器创建相应的事件,当该事件发生时,我们的监听器就会得到相应的通知,并且触发相应的逻辑。是典型的观察者模式

基本用法

@FunctionalInterface
public interface ApplicationListener<E extends ApplicationEvent> extends EventListener {

   /**
    * Handle an application event.
    * @param event the event to respond to
    */
   void onApplicationEvent(E event);
}

事件监听器是Spring为我们定义的一个接口,该接口所携带的泛型就是我们要监听的事件,我们来实现一个ApplicationListener接口

@Component
public class MyApplicationListener implements ApplicationListener<ApplicationEvent> {

    //当容器中发布此事件以后,方法触发
    @Override
    public void onApplicationEvent(ApplicationEvent event) {
        System.out.println("reveice event:  " + event);
    }
}

发布一个事件

Spring的ApplicationContext为我们提供了一个方法publishEvent()该方法可以为我们发布事件。

applicationContext.publishEvent(new ApplicationEvent(new Stirng("我发布的事件")));

原理

  1. ServletWebServerInitializedEvent的接收

    1. 在Spring refresh容器后,会执行一个finishRefresh()方法。

    2. getLifecycleProcessor().onRefresh();

    3. this.applicationContext.publishEvent(new ServletWebServerInitializedEvent(this.webServer,this.applicationContext));

    4. getApplicationEventMulticaster().multicastEvent(applicationEvent,eventType);

    5. //拿到所有符合条件的ApplicationListener,遍历它
      for (ApplicationListener<?> listener : getApplicationListeners(event, type)) {
         if (executor != null) {
            executor.execute(() -> invokeListener(listener, event));
         }
         else {
             //依次调用每个ApplicationListener的onApplicationEvent方法
            invokeListener(listener, event);
         }
      }
      
  2. 其他Event的发布和上述流程基本相符。

  3. 关于applicationEventMulticaster的注入

    protected void initApplicationEventMulticaster() {
       ConfigurableListableBeanFactory beanFactory = getBeanFactory();
        //如果容器中有APPLICATION_EVENT_MULTICASTER_BEAN_NAME,则获取该组件,并加入到applicationEventMulticaster中
       if (beanFactory.containsLocalBean(APPLICATION_EVENT_MULTICASTER_BEAN_NAME)) {
          this.applicationEventMulticaster =
                beanFactory.getBean(APPLICATION_EVENT_MULTICASTER_BEAN_NAME, ApplicationEventMulticaster.class);
          if (logger.isTraceEnabled()) {
             logger.trace("Using ApplicationEventMulticaster [" + this.applicationEventMulticaster + "]");
          }
       }
       else {
           //如果容器中没有如果容器中有APPLICATION_EVENT_MULTICASTER_BEAN_NAME,就自己创建一个单实例bean,注入到beanFactory中
          this.applicationEventMulticaster = new SimpleApplicationEventMulticaster(beanFactory);
          beanFactory.registerSingleton(APPLICATION_EVENT_MULTICASTER_BEAN_NAME, this.applicationEventMulticaster);
          if (logger.isTraceEnabled()) {
             logger.trace("No '" + APPLICATION_EVENT_MULTICASTER_BEAN_NAME + "' bean, using " +
                   "[" + this.applicationEventMulticaster.getClass().getSimpleName() + "]");
          }
       }
    }
    
  4. 容器中有哪些监听器?

protected void registerListeners() {
   // Register statically specified listeners first.
   for (ApplicationListener<?> listener : getApplicationListeners()) {
      getApplicationEventMulticaster().addApplicationListener(listener);
   }

   // Do not initialize FactoryBeans here: We need to leave all regular beans
   // uninitialized to let post-processors apply to them!
   String[] listenerBeanNames = getBeanNamesForType(ApplicationListener.class, true, false);
   for (String listenerBeanName : listenerBeanNames) {
      getApplicationEventMulticaster().addApplicationListenerBean(listenerBeanName);
   }

   // Publish early application events now that we finally have a multicaster...
   Set<ApplicationEvent> earlyEventsToProcess = this.earlyApplicationEvents;
   this.earlyApplicationEvents = null;
   if (!CollectionUtils.isEmpty(earlyEventsToProcess)) {
      for (ApplicationEvent earlyEvent : earlyEventsToProcess) {
         getApplicationEventMulticaster().multicastEvent(earlyEvent);
      }
   }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值