Monday, July 8, 2013

AbstractAnnotationConfigDispatcherServletInitializer - Long and short of it

AbstractAnnotationConfigDispatcherServletInitializer is a newly(3.2+ versions of Spring) introduced Template Method based base class that makes Spring pure java based web application Configuration(@Configuration) without using a web.xml, easier.

The use of this class can be better appreciated using an example. Prior to AbstractAnnotationConfigDispatcherServletInitializer, the way to configure a web.xml less Servlet 3 web application is by implementing a WebApplicationInitializer:

public class CustomWebAppInitializer implements WebApplicationInitializer {

 @Override
 public void onStartup(ServletContext container) {
  AnnotationConfigWebApplicationContext rootContext = new AnnotationConfigWebApplicationContext();
  rootContext.register(RootConfiguration.class);
  container.addListener(new ContextLoaderListener(rootContext));
  AnnotationConfigWebApplicationContext webContext = new AnnotationConfigWebApplicationContext();
  webContext.register(MvcConfiguration.class);
  DispatcherServlet dispatcherServlet = new DispatcherServlet(webContext);
  ServletRegistration.Dynamic dispatcher = container.addServlet("dispatcher", dispatcherServlet);
  dispatcher.addMapping("/");
 }
}

A little more detail of how WebApplicationInitializer works internally is described here

With the introduction of AbstractAnnotationConfigDispatcherServletInitializer, this configuration is now much simpler and far less error prone.

public class CustomWebAppInitializer extends AbstractAnnotationConfigDispatcherServletInitializer {
 @Override
 protected Class<?>[] getRootConfigClasses() {
  return new Class<?>[]{RootConfiguration.class};
 }

 @Override
 protected Class<?>[] getServletConfigClasses() {
  return new Class<?>[]{MvcConfiguration.class};
 }

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


Indeed a terribly long name, but the class serves to make the initialization code much more concise and clear.

1 comment: