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 theweb.xml
) by servlet container.ContextLoaderListener
creates newWebApplicationContext
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 ownWebApplicationContext
(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’sServiceLoader
. - 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 bySpringServletContainerInitializer
.- Your
WebApplicationInitializer
creates new ROOTWebApplicationContext
with XML or@Configuration
based configuration. - Your
WebApplicationInitializer
creates new servletWebApplicationContext
with XML or@Configuration
based configuration. - Your
WebApplicationInitializer
creates and registers newDispatcherServlet
with the context from previous step.
- Your
- 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).