Spring源码:initApplicationEventMulticaster源码解析

initApplicationEventMulticaster源码解析

初始化事件监听多路广播器

/**
	 * Initialize the ApplicationEventMulticaster.
	 * Uses SimpleApplicationEventMulticaster if none defined in the context.
	 * @see org.springframework.context.event.SimpleApplicationEventMulticaster
	 */
	protected void initApplicationEventMulticaster() {
		//获取Bean工厂,一般为DefaultListBeanFactory
		ConfigurableListableBeanFactory beanFactory = getBeanFactory();
		//首先判断是否已有xml文件定义了id为aplicationEventMulticaster的bean对象
		//自定义的事件监听多路广播器需要实现AplicationEventMulticaster接口
		if (beanFactory.containsLocalBean(APPLICATION_EVENT_MULTICASTER_BEAN_NAME)) {
			//如果有,则从Bean工厂得到这个bean对象
			this.applicationEventMulticaster =
					beanFactory.getBean(APPLICATION_EVENT_MULTICASTER_BEAN_NAME, ApplicationEventMulticaster.class);
			if (logger.isTraceEnabled()) {
				logger.trace("Using ApplicationEventMulticaster [" + this.applicationEventMulticaster + "]");
			}
		}
		else {
			//如果没有xml文件定义这个bean对象,那么新建一个SimpleApplicationEventMulticaster类作为aplicationEventMulticaster的Bean
			//因为SimpleApplicationEventMulticaster继承了AbstractApplicationEventMulticaster抽象类,而这个抽象类实现了aplicationEventMulticaster接口
			//因此SimpleApplicationEventMulticaster是aplicationEventMulticaster接口的一个实现
			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() + "]");
			}
		}
	}

事件的执行主要是在Bean初始化之后;就是publishEvent方法

protected void finishRefresh() {
		// Clear context-level resource caches (such as ASM metadata from scanning).
		//清除缓存尤其是扫描过程中像ASM的数据
		clearResourceCaches();

		// Initialize lifecycle processor for this context.
		//为上下文初始化生命周期处理器
		initLifecycleProcessor();

		// Propagate refresh to lifecycle processor first.
		//首先传播刷新生命周期处理器
		getLifecycleProcessor().onRefresh();

		// Publish the final event.
		//发布事件
		publishEvent(new ContextRefreshedEvent(this));

		// Participate in LiveBeansView MBean, if active.
		LiveBeansView.registerApplicationContext(this);
	}
/**
	 * Publish the given event to all listeners.
	 * @param event the event to publish (may be an {@link ApplicationEvent}
	 * or a payload object to be turned into a {@link PayloadApplicationEvent})
	 * @param eventType the resolved event type, if known
	 * @since 4.2
	 */
	protected void publishEvent(Object event, @Nullable ResolvableType eventType) {
		Assert.notNull(event, "Event must not be null");

		// Decorate event as an ApplicationEvent if necessary
		//如有必要,将事件装饰为ApplicationEvent
		ApplicationEvent applicationEvent;
		if (event instanceof ApplicationEvent) {
			applicationEvent = (ApplicationEvent) event;
		}
		else {
			//不是事件就转为事件
			applicationEvent = new PayloadApplicationEvent<>(this, event);
			if (eventType == null) {
				eventType = ((PayloadApplicationEvent<?>) applicationEvent).getResolvableType();
			}
		}

		// Multicast right now if possible - or lazily once the multicaster is initialized
		//如果可能,立即进行多播-或一旦初始化多播器就懒惰
		if (this.earlyApplicationEvents != null) {
			this.earlyApplicationEvents.add(applicationEvent);
		}
		else {
			//获取事件广播器,发布事件
			getApplicationEventMulticaster().multicastEvent(applicationEvent, eventType);
		}

		// Publish event via parent context as well...
		//如果存在父容器,那么父容器也发布事件
		if (this.parent != null) {
			if (this.parent instanceof AbstractApplicationContext) {
				((AbstractApplicationContext) this.parent).publishEvent(event, eventType);
			}
			else {
				this.parent.publishEvent(event);
			}
		}
	}

具体的发布逻辑在multicastEvent方法中

@Override
	public void multicastEvent(final ApplicationEvent event, @Nullable ResolvableType eventType) {
		ResolvableType type = (eventType != null ? eventType : resolveDefaultEventType(event));
		Executor executor = getTaskExecutor();
		//遍历所有监听器
		for (ApplicationListener<?> listener : getApplicationListeners(event, type)) {
			if (executor != null) {
			//执行监听器的方法
				executor.execute(() -> invokeListener(listener, event));
			}
			else {
				invokeListener(listener, event);
			}
		}
	}

这个逻辑也很简单,无非就是启动一个线程池,去调用这些监听器的处理这些事件的方法

猜你喜欢

转载自blog.csdn.net/StrawberryMuMu/article/details/103088555
今日推荐