10

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?

1
  • I had the same problem. Removing the @EventListener solved the problem. Would someone have an explanation? Apr 29, 2017 at 17:22

2 Answers 2

12

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.

4
  • 6
    Thank you. I ruled it out with an e.getApplicationContext().getParent() != null, but it seems a bit hacky. I wonder if there is a better practice around? Jan 9, 2015 at 11:20
  • Not really, you could toggle a boolean if the listener was already invoked. If it is just to load some data and you are using Spring 4.1 you could also use the SmartInitializingSingleton instead.
    – M. Deinum
    Jan 9, 2015 at 11:31
  • You may also wish to ensure that the web context does not instantiate any beans other than your controllers. i.e. Enforce the component scan base packages to only include a 'web' package, which is parent to controllers and other such beans. This ought to ensure that your listener only exists in the root context, and will therefore only pick up root context events.
    – Steve
    Jan 9, 2015 at 12:03
  • Thanks, looking at event.applicationcontext (id, and parent and grandparent) (in our case for the closeEvent) gave us a better understanding of the context configuration and hierarchy of each caller (servlet ctx in addition to the root app context).
    – boly38
    Apr 2, 2021 at 14:12
-1

Do not annotated your Listener Class's method with @EventListener

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.