How is Spring actually bootstrap?

java, spring, spring-mvc

Solution

Servlet context listener (web.xml) approach

- A web application WAR is being deployed by user.

- Servlet container (Tomcat) reads `web.xml`.

- Servlet context listener `ContextLoaderListener` is being instantiated (if defined as `<listener>` inside the `web.xml`) by servlet container.

- `ContextLoaderListener` creates new `WebApplicationContext` with application context XML configuration.

- Your ROOT context beans are registered and instantiated by `BeanFactory` inside the application context.

- `DispatcherServlet` is being instantiated by servlet container.

- `DispatcherServlet` creates its own `WebApplicationContext` (`WEB-INF/{servletName}-servlet.xml` by default) with the ROOT context as its parent.

- Your servlet beans are registered and instantiated by `BeanFactory` inside the application context.

- `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.

- A web application WAR is being deployed by user.

- Servlet container searches for classes implementing `ServletContainerInitializer` via Java's `ServiceLoader`.

- Spring's `SpringServletContainerInitializer` is found and instantiated by servlet container.

- Spring's initializer reads web application's class-path and searches for `WebApplicationInitializer` implementations.

- Your `WebApplicationInitializer` is found (btw. check its JavaDoc!!!) and instantiated by `SpringServletContainerInitializer`.

- Your `WebApplicationInitializer` creates new ROOT `WebApplicationContext` with XML or `@Configuration` based configuration.

- Your `WebApplicationInitializer` creates new servlet `WebApplicationContext` with XML or `@Configuration` based configuration.

- Your `WebApplicationInitializer` creates and registers new `DispatcherServlet` with the context from previous step.

- 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).

Problem

- Does anybody know how Spring is actually bootstraps? - Which instances created and by whom? - I really want to know who creates instances of WebApplicationContext and ContextLoader. Is it work of Tomcat?

Original source