1 简述Spring的生命周期
不论是Spring的监听机制原理还是Spring AOP的原理,都是依托于Spring的生命周期,所以要了解Spring的监听机制原理就需要先了解Spring的生命周期
简述Spring生命周期
1 创建类扫描器和注解解析器赋值给BeanFactory
2 将传入的主配置类的信息封装成BeanDefinition放入BeanFactory的BeanDefinitionMap
3 根据主配置的BeanDefinition去扫描所有的Bean类,并且将相应的类信息封装成BeanDefinition放入BeanDefinitionMap
4 注册后置处理器(将后置处理器创建实例放入容器)
5 初始化事件广播器
6 完成Bean的初始化
在Bean的初始化阶段,有许多的后置处理器阶段,最重要的,使用最多的就是初始化后的后置处理器阶段
2 简述Spring 事件监听原理
SimpleApplicationEventMulticaster:事件广播器
/**
* Helper class that encapsulates a general set of target listeners.
*/
private class DefaultListenerRetriever {
//保存事件监听器
public final Set<ApplicationListener<?>> applicationListeners = new LinkedHashSet<>();
public final Set<String> applicationListenerBeans = new LinkedHashSet<>();
public Collection<ApplicationListener<?>> getApplicationListeners() {
List<ApplicationListener<?>> allListeners = new ArrayList<>(
this.applicationListeners.size() + this.applicationListenerBeans.size());
allListeners.addAll(this.applicationListeners);
if (!this.applicationListenerBeans.isEmpty()) {
BeanFactory beanFactory = getBeanFactory();
for (String listenerBeanName : this.applicationListenerBeans) {
try {
ApplicationListener<?> listener =
beanFactory.getBean(listenerBeanName, ApplicationListener.class);
if (!allListeners.contains(listener)) {
allListeners.add(listener);
}
}
catch (NoSuchBeanDefinitionException ex) {
// Singleton listener instance (without backing bean definition) disappeared -
// probably in the middle of the destruction phase
}
}
}
AnnotationAwareOrderComparator.sort(allListeners);
return allListeners;
}
}
//在事件广播器中,有一个内部类,用于保存所有的时间监听器
1 在Spring的生命周期中,会自动初始化事件广播器(SimpleApplicationEventMulticaster)
2 在Spring的生命周期的初始化后的后置处理器阶段,会将每一个Bean都判断一下,当前Bean是不是实现了ApplicationListener接口,如果实现了此接口,那就将当前Bean放入监听器集合中
3 当在业务中使用上下文发布事务时,会使用事件广播器对象调用筛选方法,根据传入的事件,筛选出与之对应的所有事件监听器集合,然后变量这个集合,在遍历集合的过程中,如果Executor对为null,那是就直接执行监听器的回调方法,如果Executor不为null,那么开启一个线程去执行监听器的回调方法(异步)