Skip to content

Instantly share code, notes, and snippets.

@nickebbutt
Created September 12, 2019 10:05
Show Gist options
  • Save nickebbutt/d5875844d03a60a387938d0bc6d6109a to your computer and use it in GitHub Desktop.
Save nickebbutt/d5875844d03a60a387938d0bc6d6109a to your computer and use it in GitHub Desktop.
Wait for dispatcher servlet initialization to complete from a bean in the Spring MVC application context

Problem:

Spring MVC apps are typically split into an application context, which is initialized using org.springframework.web.context.ContextLoaderListener, and one or more dispatcher servlet contexts, which provide the 'front controller' for the web application and initialize the http/https endpoints.

This allow the app to be composed in two layers - The application beans know nothing about the existence of the dispacher servlet or web endpoints. However beans in the dispacher servlet are created in a child context of the main application context, and may know about the application beans.

This works well, but there are times when beans in the application layer do need to know that the web container endpoints have finished initialization - and that the app is accessible to the outside world.

Solution:

The solution I found for this is to implement ApplicationListener in an application bean, and listen for ContextRefreshedEvent. However, two instances of this event will be received - one for the main application context, and the second for the child context which contains dispatcher servlet. We need to wait to receive the event which relates to the child context.

public class MyApplicationBean implements ApplicationListener<ContextRefreshedEvent> {
@Override
public void onApplicationEvent(ContextRefreshedEvent event) {
//wait for the child dispatcher servlet context to be initialized which should mean the http:// endpoints are available
if ( event.getApplicationContext().getId().contains("dispatcher")) {
... do whatever we need to do here
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment