1.applicationListener总是和contextrefreshedevent相对出现
在spring的ioc容器初始化完成后,ioc容器会发布一个事件的动作,从AbstractApplicationContext类中的
protected void finishRefresh() {
initLifecycleProcessor();
getLifecycleProcessor().onRefresh();
// Publish the final event.
publishEvent(new ContextRefreshedEvent(this));
LiveBeansView.registerApplicationContext(this);
}publishEvent可以看出。
这样,我们在自定义类实现了ApplicationListener<ContextRefreshedEvent>,重写了
onApplicationEvent方法,当ioc容器发布这个事件动作后,我们就能接收到事件了
2.在web项目中,application context有两个容器,一个是root application context,一个是serlet context子容器,所以这两个容器初始化完成后都会发布这个事件,所以onApplicationEvent方法将会调用两个,为了防止onApplicationEvent方法执行两次,我们可以if判断符合:ContextRefreshedEvent.getApplication().getParent()限制到父容器才去执行我们需要的逻辑代码。因为root application context本身就是最上级的容器,所以他没有父容器,但是servletcontext的父容器是root application context。
本文深入探讨了Spring框架中ApplicationListener与ContextRefreshedEvent的关系,解释了如何通过实现ApplicationListener<ContextRefreshedEvent>来监听IOC容器的初始化完成事件,并在Web项目中避免重复触发事件的方法。
655





