源码分析
先看代码
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!
//获取我们注册进ioc的ApplicationListener监听器,并与上述事件多播器绑定
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);
}
}
}
上述代码知性逻辑比较简单:获取默认和我们注册的监听器,将其实例化并与事件多播器绑定,实现观察者模式,对这个过程触发的事件进行监听。
使用示例
实现ApplicationListener接口
public class MyApplicationListener implements ApplicationListener {
@Override
public void onApplicationEvent(ApplicationEvent event) {
System.out.println(event);
}
}
注册为bean
<bean id="listener" class="com.youzm.Ioc.post.MyApplicationListener"></bean>