Spring ApplicationListener在webapp上被触发两次

时间:2015-01-09 11:07:12

标签: spring spring-mvc

我有一个应用程序监听器,它应该每个webapp启动只执行一次,因为它加载了基本的用户信息数据。

public class DefaultUsersDataLoader implements ApplicationListener<ContextRefreshedEvent> {
  @Override
  @Transactional
  public void onApplicationEvent(ContextRefreshedEvent e) {...}
}

不知何故,它会被执行两次:在应用启动时和第一个请求到达服务器时。为什么会发生这种情况?如何防止它?

2 个答案:

答案 0 :(得分:11)

通常在Spring MVC应用程序中,您同时拥有ContextLoaderListenerDispatcherServlet。这两个组件都会创建自己的ApplicationContext,而这两个组件都会触发ContextRefreshedEvent

DispatcherServlet使用ApplicationContext创建的ContextLoaderListener作为其父级。从子上下文触发的事件将传播到父上下文。

现在,如果您在根上下文中定义了ApplicationListener<ContextRefreshedEvent>(由ContextLoaderListener加载的那个),它将收到两次事件。

答案 1 :(得分:0)

不要使用@EventListener

注释您的Listener类的方法