See http://docs.spring.io/spring/docs/4.0.x/spring-framework-reference/htmlsingle/#context-create.
The principle is to declare a ServletContextListener in the standard webapp descriptor (web.xml). Such a listener is indeed instantiated by the container and is called when the application is initialized and when it's destroyed.
Spring provides such a ServletContextListener: ContextLoaderListener which, as its name indicates, loads a Spring context when the webapp is initialized.
web.xml
.<listener>
inside the web.xml
) by servlet container.
ContextLoaderListener
creates new WebApplicationContext with application context XML configuration.BeanFactory
inside the application context.DispatcherServlet
creates its own WebApplicationContext
(WEB-INF/{servletName}-servlet.xml
by default) with the ROOT context as its parent.DispatcherServlet
registers some default beans in case you did not provide them yourself.This one is possible with Servlet 3 features.
WebApplicationInitializer
is found (btw. check its JavaDoc!!!) and instantiated by SpringServletContainerInitializer
.
WebApplicationInitializer
creates new ROOT WebApplicationContext with XML or @Configuration
based configuration.WebApplicationInitializer
creates new servlet WebApplicationContext with XML or @Configuration
based configuration.WebApplicationInitializer
creates and registers new DispatcherServlet
with the context from previous step.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).