Spring MVC can be bootstrapped entirely in Java, without a web.xml file, by implementing WebApplicationInitializer. Servlet 3.0+ containers detect this interface automatically at startup and use it to register DispatcherServlet, replacing the older XML-based deployment descriptor.
Key Points: • A class implementing WebApplicationInitializer overrides onStartup(ServletContext) and is picked up automatically by any Servlet 3.0+ container via SpringServletContainerInitializer. • Inside onStartup, an AnnotationConfigWebApplicationContext is created and DispatcherServlet is registered against it programmatically. • A @Configuration class annotated with @EnableWebMvc replaces the old <mvc:annotation-driven/> XML configuration, activating annotation-based mapping. • Spring provides AbstractAnnotationConfigDispatcherServletInitializer as a convenience base class that handles most of this boilerplate for typical setups. • Spring Boot takes this further by embedding the servlet container itself, so there's no external container or explicit initializer needed at all — just a main() method.
Example: Extending AbstractAnnotationConfigDispatcherServletInitializer and overriding getServletMappings() to return "/" plus getRootConfigClasses()/getServletConfigClasses() to point at @Configuration classes is enough to fully replace a traditional web.xml setup.
Code Example:
public class AppInitializer extends AbstractAnnotationConfigDispatcherServletInitializer {
@Override
protected Class<?>[] getRootConfigClasses() {
return new Class<?>[] { RootConfig.class };
}
@Override
protected Class<?>[] getServletConfigClasses() {
return new Class<?>[] { WebConfig.class };
}
@Override
protected String[] getServletMappings() {
return new String[] { "/" };
}
}Interview Tip: A concise interview answer is:
"Without web.xml, I'd implement WebApplicationInitializer, or more conveniently extend AbstractAnnotationConfigDispatcherServletInitializer, which registers DispatcherServlet programmatically against Java @Configuration classes annotated with @EnableWebMvc. Servlet 3.0+ containers pick this up automatically at startup, and Spring Boot goes even further by embedding the container so there's no initializer to write at all."