Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring ApplicationListener gets fired twice on 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?

like image 329
Pedro Montoto García Avatar asked Jan 09 '15 11:01

Pedro Montoto García


1 Answers

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.

The DispatcherServlet uses the ApplicationContext as created by the ContextLoaderListener as its parent. Events fired from child contexts are propagated to the parent context.

Now if you have an ApplicationListener<ContextRefreshedEvent> defined in the root context (the one loaded by the ContextLoaderListener) it will receive an event twice.

like image 190
M. Deinum Avatar answered Sep 19 '22 19:09

M. Deinum