转自:https://www.cnblogs.com/halu126/p/ContextRefreshedEvent.html
在应用启动时,通常想在此时预加载一些资源,全局使用。
Spring会在操作应用上下文时,使用ApplicationEventPublisher触发相关ApplicationContextEvent,我们可以监听这些事件来做一些事情。
Spring中ApplicationContextEvent有以下几种:
其中ContextRefreshedEvent的执行时机为:
我们通常会在Spring加载或刷新应用上下文时,也重新刷新下我们预加载的资源,我们就可以通过监听ContextRefreshedEvent来做这样的事情。
代码如下:
@Component
public class SpringHandlersProvider implements ApplicationListener<ContextRefreshedEvent> {
Lists<XXX> handlerList = Lists.newHashList();
@Override
public void onApplicationEvent(ContextRefreshedEvent event) {
//do something
handlerList.add(xxx);
}
}
但对于tomcat工程来说,我们一般会加载两个上下文容器一个父容器,一个mvc子容器
- 父容器{@code ContextRefreshedEvent[source=Root WebApplicationContext: startup date [Thu Sep 29 14:52:08 CST 2016]; root of context hierarchy]}
- mvc容器{@code ContextRefreshedEvent[source=WebApplicationContext for namespace 'springmvc-servlet': startup date [Thu Sep 29 14:52:34 CST 2016]; parent: Root WebApplicationContext]}
这样就会触发两次ContextRefreshedEvent事件,导致监听此事件所作的逻辑执行两次。
避免方法:
1:只在加载父容器时,执行一次
@Component
public class SpringHandlersProvider implements ApplicationListener<ContextRefreshedEvent> {
Lists<XXX> handlerList = Lists.newHashList();
@Override
public void onApplicationEvent(ContextRefreshedEvent event) {
if (Predicates.isNull().apply(event.getApplicationContext().getParent())) {
//do something
handlerList.add(xxx);
}
}
}
2:每次执行onApplicationEvent()方法时就将存放资源的容器清空下
@Component
public class SpringHandlersProvider implements ApplicationListener<ContextRefreshedEvent> {
Lists<XXX> handlerList = Lists.newHashList();
@Override
public void onApplicationEvent(ContextRefreshedEvent event) {
handlerList.clear();
//do something
handlerList.add(xxx);
}
}