Spring MVC and Servlets 3.0 - Do you still need web.xml?

With JEE6, if your application container is Servlet 3.0 ready what you need to do is:

  1. Create a custom class that implements ServletContainerInitializer (i.e. com.foo.FooServletContainer)
  2. Create a file in your META-INF/services folder named javax.servlet.ServletContainerInitializer which will contain the name of your implementation above (com.foo.FooServletContainer)

Spring 3 is bundled with a class named SpringServletContainerInitializer that implements the stuff above (so you don't need to create yourself the file in META-INF/services. This class just calls an implementation of WebApplicationInitializer. So you just need to provide one class implementing it in your classpath (the following code is taken from the doc above).

public class FooInitializer implements WebApplicationInitializer {
    @Override
    public void onStartup(ServletContext servletContext) {
        WebApplicationContext appContext = ...;

        ServletRegistration.Dynamic dispatcher =
           container.addServlet("dispatcher", new DispatcherServlet(appContext));
        dispatcher.setLoadOnStartup(1);
        dispatcher.addMapping("/");
    }
 }

That's it for the web.xml thing, but you need to configure the webapp using @Configuration, @EnableWebMvc etc..


Yes you don't need web.xml to startup your webapp Servlet 3.0+. As Alex already mentioned you can implement WebApplicationInitializer class and override onStartup() method. WebApplicationInitializer is an interface provided by Spring MVC that ensures your implementation is detected and automatically used to initialize any Servlet 3 container.

Is there a way to configure your full Spring application without any xml?

Adding this answer just to add another way. You don't need to implement WebApplicationInitializer. An abstract base class implementation of WebApplicationInitializer named AbstractDispatcherServletInitializer makes it even easier to register the DispatcherServlet by simply overriding methods to specify the servlet mapping and the location of the DispatcherServlet configuration -

public class MyWebAppInitializer extends AbstractDispatcherServletInitializer {

    @Override
    protected WebApplicationContext createRootApplicationContext() {
        return null;
    }

    @Override
    protected WebApplicationContext createServletApplicationContext() {
        XmlWebApplicationContext cxt = new XmlWebApplicationContext();
        cxt.setConfigLocation("/WEB-INF/spring/dispatcher-config.xml");
        return cxt;
    }

    @Override
    protected String[] getServletMappings() {
        return new String[] { "/" };
    }

}