0
点赞
收藏
分享

微信扫一扫

spring核心源码分析第十四篇 refresh流程之initApplicationEventMulticaster

小月亮06 2022-01-04 阅读 24

文章目录

广播器源码分析

  • 创建一个广播器并注册到bean工厂
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.isTraceEnabled()) {
				logger.trace("Using ApplicationEventMulticaster [" + this.applicationEventMulticaster + "]");
			}
		}
		else {
		创建一个广播器并注册到bean工厂
			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() + "]");
			}
		}
	}

使用方式

		ApplicationContext applicationContext = new AnnotationConfigApplicationContext();
        applicationContext.publishEvent(new ApplicationEvent("event") {
            @Override
            public Object getSource() {
                return super.getSource();
            }
        });

监听方式

public interface ApplicationListener<E extends ApplicationEvent> extends EventListener {
	void onApplicationEvent(E event);
}
举报

相关推荐

0 条评论