Spring ApplicationListener 在 webapp 上被触发了两次
Spring ApplicationListener gets fired twice on webapp
我有一个应用程序侦听器,它应该在每次 webapp 启动时只执行一次,因为它会加载基本的用户信息数据。
public class DefaultUsersDataLoader implements ApplicationListener<ContextRefreshedEvent> {
@Override
@Transactional
public void onApplicationEvent(ContextRefreshedEvent e) {...}
}
不知何故,它被执行了两次:在应用程序启动时和第一个请求到达服务器时。为什么会发生这种情况,我该如何预防?
通常在 Spring MVC 应用程序中,您同时拥有 ContextLoaderListener
和 DispatcherServlet
。两个组件都创建了自己的 ApplicationContext
,这又会触发 ContextRefreshedEvent
.
DispatcherServlet
使用 ContextLoaderListener
创建的 ApplicationContext
作为其父级。从子上下文触发的事件被传播到父上下文。
现在,如果您在根上下文(由 ContextLoaderListener
加载的上下文)中定义了一个 ApplicationListener<ContextRefreshedEvent>
,它将收到两次事件。
不要使用 @EventListener
注释您的监听器 Class 的方法
我有一个应用程序侦听器,它应该在每次 webapp 启动时只执行一次,因为它会加载基本的用户信息数据。
public class DefaultUsersDataLoader implements ApplicationListener<ContextRefreshedEvent> {
@Override
@Transactional
public void onApplicationEvent(ContextRefreshedEvent e) {...}
}
不知何故,它被执行了两次:在应用程序启动时和第一个请求到达服务器时。为什么会发生这种情况,我该如何预防?
通常在 Spring MVC 应用程序中,您同时拥有 ContextLoaderListener
和 DispatcherServlet
。两个组件都创建了自己的 ApplicationContext
,这又会触发 ContextRefreshedEvent
.
DispatcherServlet
使用 ContextLoaderListener
创建的 ApplicationContext
作为其父级。从子上下文触发的事件被传播到父上下文。
现在,如果您在根上下文(由 ContextLoaderListener
加载的上下文)中定义了一个 ApplicationListener<ContextRefreshedEvent>
,它将收到两次事件。
不要使用 @EventListener
注释您的监听器 Class 的方法