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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With