Spring ApplicationListener在webapp上被触发了两次 [英] Spring ApplicationListener gets fired twice on webapp
问题描述
我有一个应用程序侦听器,由于它会加载基本的用户信息数据,因此应该在每次webapp启动时仅执行一次.
I have an application listener that's supposed to execute only once per webapp startup, since it loads basic user info data.
public class DefaultUsersDataLoader implements ApplicationListener<ContextRefreshedEvent> {
@Override
@Transactional
public void onApplicationEvent(ContextRefreshedEvent e) {...}
}
以某种方式,它执行两次:在应用程序启动时以及第一个请求到达服务器时.为什么会发生这种情况,我该如何预防呢?
Somehow, it gets executed twice: on app startup and when the first request arrives to the server. Why is this happening and how can I prevent it?
推荐答案
通常在Spring MVC应用程序中,您同时具有ContextLoaderListener
和DispatcherServlet
.这两个组件都创建了自己的ApplicationContext
,这又触发了ContextRefreshedEvent
.
Generally in a Spring MVC application you have both a ContextLoaderListener
and DispatcherServlet
. Both components create their own ApplicationContext
which in turn both fire a ContextRefreshedEvent
.
DispatcherServlet
使用由ContextLoaderListener
创建的ApplicationContext
作为其父级.从子上下文触发的事件将传播到父上下文.
The DispatcherServlet
uses the ApplicationContext
as created by the ContextLoaderListener
as its parent. Events fired from child contexts are propagated to the parent context.
现在,如果您在根上下文中定义了ApplicationListener<ContextRefreshedEvent>
(由ContextLoaderListener
加载的那个),它将收到两次事件.
Now if you have an ApplicationListener<ContextRefreshedEvent>
defined in the root context (the one loaded by the ContextLoaderListener
) it will receive an event twice.
这篇关于Spring ApplicationListener在webapp上被触发了两次的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!