How to configure dispatcher servlet without web.xml?
In my first post I want show you how to simply configure Dispatcher Servlet with Spring without xml code.
I will cover three types of spring configuration you may want to use(I think about cofiguration of rest of application, not about dispatcher servlet).
Java annotations driven config, xml based and mixture of both of them.
In configuration I will WebApplicationInitializer interface and AbstractDispatcherServletInitializer class.
When you want to configure dispatcher servlet in java you probably should use one of them.
Configuration by implementing WebApplicationInitializer interface:
import org.springframework.web.WebApplicationInitializer; public class MyWebApplicationInitializer implements WebApplicationInitializer { @Override public void onStartup(ServletContext container) { XmlWebApplicationContext appContext = new XmlWebApplicationContext(); appContext.setConfigLocation("/WEB-INF/spring/dispatcher-config.xml"); ServletRegistration.Dynamic registration = container.addServlet("dispatcher", new DispatcherServlet(appContext)); registration.setLoadOnStartup(1); registration.addMapping("/"); } }
Configuration by extending AbstractDispatcherServletInitializer(for using xml based spring 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[] { "/" }; } }
Configuration by extending AbstractAnnotationConfigDispatcherServletInitializer class(for java based spring configuration):
public class MyWebAppInitializer extends AbstractAnnotationConfigDispatcherServletInitializer { @Override protected Class<!--?-->[] getRootConfigClasses() { return null; } @Override protected Class<!--?-->[] getServletConfigClasses() { return new Class[] { MyWebConfig.class }; } @Override protected String[] getServletMappings() { return new String[] { "/" }; } }
Links:
http://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/web/WebApplicationInitializer.html
http://docs.spring.io/spring/docs/current/spring-framework-reference/html/mvc.html#mvc-container-config