How is Spring actually bootstrap?

Servlet context listener (web.xml) approach

  1. A web application WAR is being deployed by user.
  2. Servlet container (Tomcat) reads web.xml.
  3. Servlet context listener ContextLoaderListener is being instantiated (if defined as <listener> inside the web.xml) by servlet container.
    1. ContextLoaderListener creates new WebApplicationContext with application context XML configuration.
    2. Your ROOT context beans are registered and instantiated by BeanFactory inside the application context.
  4. DispatcherServlet is being instantiated by servlet container.
    1. DispatcherServlet creates its own WebApplicationContext (WEB-INF/{servletName}-servlet.xml by default) with the ROOT context as its parent.
    2. Your servlet beans are registered and instantiated by BeanFactory inside the application context.
    3. DispatcherServlet registers some default beans in case you did not provide them yourself.

Servlet container initializer (non web.xml) approach

This one is possible with Servlet 3 features.

  1. A web application WAR is being deployed by user.
  2. Servlet container searches for classes implementing ServletContainerInitializer via Java’s ServiceLoader.
  3. Spring’s SpringServletContainerInitializer is found and instantiated by servlet container.
  4. Spring’s initializer reads web application’s class-path and searches for WebApplicationInitializer implementations.
  5. Your WebApplicationInitializer is found (btw. check its JavaDoc!!!) and instantiated by SpringServletContainerInitializer.
    1. Your WebApplicationInitializer creates new ROOT WebApplicationContext with XML or @Configuration based configuration.
    2. Your WebApplicationInitializer creates new servlet WebApplicationContext with XML or @Configuration based configuration.
    3. Your WebApplicationInitializer creates and registers new DispatcherServlet with the context from previous step.
  6. Servlet container finishes the web application initialization and instantiates components which were registered by their class in previous steps (none in my example).

Java based approach is much more flexible. You can leave the context creation to DispatcherServlet or even the whole instantiation of DispatcherServlet itself to servlet container (just register servlet DispatcherServlet.class instead of its instance).

Leave a Comment