找找 Spring Event 源码中各种设计模式的使用

本文将按照Spring Event 是什么鬼的思路寻找 Spring 源码中与 Spring Event 有关的设计模式实现


初始化-工厂模式

AbstractApplicationContext.java
/**
 * Initialize the ApplicationEventMulticaster.
 * Uses SimpleApplicationEventMulticaster if none defined in the context.
 * @see org.springframework.context.event.SimpleApplicationEventMulticaster
 */
protected void initApplicationEventMulticaster() {
   ConfigurableListableBeanFactory beanFactory = getBeanFactory();
   if (beanFactory.containsLocalBean(APPLICATION_EVENT_MULTICASTER_BEAN_NAME)) {
      this.applicationEventMulticaster =
            beanFactory.getBean(APPLICATION_EVENT_MULTICASTER_BEAN_NAME, ApplicationEventMulticaster.class);
      if (logger.isDebugEnabled()) {
         logger.debug("Using ApplicationEventMulticaster [" + this.applicationEventMulticaster + "]");
      }
   }
   else {
      this.applicationEventMulticaster = new SimpleApplicationEventMulticaster(beanFactory);
      beanFactory.registerSingleton(APPLICATION_EVENT_MULTICASTER_BEAN_NAME, this.applicationEventMulticaster);
      if (logger.isDebugEnabled()) {
         logger.debug("Unable to locate ApplicationEventMulticaster with name '" +
               APPLICATION_EVENT_MULTICASTER_BEAN_NAME +
               "': using default [" + this.applicationEventMulticaster + "]");
      }
   }
}

Mulicater的创建过程就是通过bean 工厂创建,此处使用了工厂模式,BeanFactory 接口定义了 getBean 方法,AbstractBeanFactory 实现了getBean方法,而针对 Bean 的管理(   Bean的定义、Bean的创建以及对Bean的解析)AbstractXXXBeanFactory等抽象类来管理,不同的抽象类有不同的管理策略。

事件发布-观察者模式

//AbstractApplicationEventMulticaster.java
    public void multicastEvent(final ApplicationEvent event) {
        for (final ApplicationListener listener : getApplicationListeners(event)) {
            Executor executor = getTaskExecutor();
            if (executor != null) {
                executor.execute(new Runnable() {
                    public void run() {
                        listener.onApplicationEvent(event);
                    }
                });
            }
            else {
                listener.onApplicationEvent(event);
            }
        }
    }

根据 event,找到监听的 listener,在事件触发时,调用 listener 的 onApplicationEvent(event) 方法,此处观察者模式的运用得益于 ApplicationEvent ApplicationListener 两个接口的定义,Spring 通过 Listener 的监听方法参数与实际触发的事件对象匹配来区别是否应该调用Listener的 onApplicationEvent 方法。


转载于:https://my.oschina.net/mays/blog/656187

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值