te the 'root' Spring application context AnnotationConfigWebApplicationContext rootContext = new AnnotationConfigWebApplicationContext(); rootContext.register(AppConfig.class); // Manage the lifecycle of the root application context container.addListener(new ContextLoaderListener(rootContext)); // Create the dispatcher servlet's Spring application context AnnotationConfigWebApplicationContext dispatcherContext = new AnnotationConfigWebApplicationContext(); dispatcherContext.register(DispatcherConfig.class); // Register and map the dispatcher servlet ServletRegistration.Dynamic dispatcher = container.addServlet("dispatcher", new DispatcherServlet(dispatcherContext)); dispatcher.setLoadOnStartup(1); dispatcher.addMapping("/"); } } As an alternative to the above, you can also extend from {@link org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer}. Remember that {@code WebApplicationInitializer} implementations are
detectedautomatically -- so you are free to package them within your application as you see fit.
Ordering {@code WebApplicationInitializer} execution
{@code WebApplicationInitializer} implementations may optionally be annotated at theclass level with Spring's @ {@link org.springframework.core.annotation.Order Order}annotation or may implement Spring's {@link org.springframework.core.Ordered Ordered}interface. If so, the initializers will be ordered prior to invocation. This provides a mechanism for users to ensure the order in which servlet container initialization occurs. Use of this feature is expected to be rare, as typical applications will likely centralize all container initialization within a single {@code WebApplicationInitializer}.
Caveats
web.xml versioning
{@code WEB-INF/web.xml} and {@code WebApplicationInitializer} use are not mutuallyexclusive; for example, web.xml can register one servlet, and a {@code WebApplicationInitializer} can register another. An initializer can evenmodify registrations performed in {@code web.xml} through methods such as{@link ServletContext#getServletRegistration(String)}. However, if {@code WEB-INF/web.xml} is present in the application, its {@code version} attributemust be set to "3.0" or greater, otherwise {@code ServletContainerInitializer}bootstrapping will be ignored by the servlet container.
Mapping to '/' under Tomcat
Apache Tomcat maps its internal {@code DefaultServlet} to "/", and on Tomcat versions<= 7.0.14, this servlet mapping cannot be overridden programmatically. 7.0.15 fixes this issue. Overriding the "/" servlet mapping has also been tested successfully under GlassFish 3.1.
@author Chris Beams
@since 3.1
@see SpringServletContainerInitializer
@see org.springframework.web.context.AbstractContextLoaderInitializer
@see org.springframework.web.servlet.support.AbstractDispatcherServletInitializer
@see org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer