Spring ApplicationListener runs twice on webapp

I have an application listener that should only run once when the webapp starts, since it loads the basic user information data.

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

Somehow, it starts twice: when you start the application and when you first access the server. Why is this happening and how can I prevent it?

+6
source share
2 answers

Typically, a Spring MVC application has both a ContextLoaderListener and a DispatcherServlet . Both components create their own ApplicationContext , which in turn runs a ContextRefreshedEvent .

DispatcherServlet uses ApplicationContext as created by ContextLoaderListener as a 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 ContextLoaderListener ), it will receive the event twice.

+11
source

Do not comment on your listener class method with @EventListener

0
source

Source: https://habr.com/ru/post/980757/


All Articles