03--ApplicationListener用法与原理

import org.springframework.context.ApplicationEvent;
import org.springframework.context.ApplicationListener;
import org.springframework.stereotype.Component;

@Component
public class MyApplicationListener implements ApplicationListener<ApplicationEvent> {

	@Override
	public void onApplicationEvent(ApplicationEvent event) {
		// TODO Auto-generated method stub
		System.out.println("收到事件"+event);
	}

}

ApplicationListener:

监听容器中发布的事件

步骤:

   1)、写一个监听器监听某个事件(ApplicationEvent及其子类)

   2)、把监听器加入到容器;

   3)、只要容器中有相关事件的发布,我们就能监听到这个事件

                 ContextRefreshedEvent:容器刷新完成(所有bean都完全创建)会发布这个事件;

                 ContextClosedEvent:关闭容器会发布这个事件,

   4)、怎么发布一个事件

https://www.cnblogs.com/lwcode6/p/12072202.html

原理:

ContextRefreshedEvent、IOCTest_Ext$1[source=我发布的时间]、ContextClosedEvent

1)、容器创建对象:refresh()

2)、finishRefresh();容器刷新完成会发布ContextRefreshedEvent事件

3)、自己发布事件

4)、如期关闭发布事件ContextClosedEvent;

【事件发布流程】: 

publishEvent(new ContextRefreshedEvent(this));

 1)、事件的多播器(派发器):getApplicationEventMulticaster()

2)、multicastEvent派发事件

3)、获取到所有的ApplicationListener

           for (ApplicationListener<?> listener : getApplicationListeners(event, type))

           1)、如果有Executor,可以支持使用Executor进行异步派发

                      Executor executor = getTaskExecutor();

          2)、否则同步的方式直接执行Listener方法:invokeListener(listener, event);

                      拿到listener回调 onApplicationEvent()方法;

 

【事件多播器(派发器)】

1)、容器创建对象:onRefresh();

2)、initApplicationEventMulticaster();初始化ApplicationEventMulticaster;

                 1)、先去容器中找没有id=“applicationEventMulticaster”的组件

                 2)、如果没有this.applicationEventMulticaster = new SimpleApplicationEventMulticaster(beanFactory);

                             并且加入到容器中,我们就可以再其他组件要派发事件,自动注入applicationEventMulticaster

【容器中有那些监听器】

        1)、容器创建对象:onRefresh();

        2)、registerListeners()

                    从容器中拿到所有的监听器,把他们注册到applicationEventMulticaster中;

                   String[] listenerBeanNames = getBeanNamesForType(ApplicationListener.class, true, false);

                  //将Listener注册到ApplicationEventMulticaster中

                 getApplicationEventMulticaster().addApplicationListenerBean(listenerBeanName);

 

 

 

 

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值