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 {

 public void onStartup(ServletContext container) {
  AnnotationConfigWebApplicationContext rootContext = new AnnotationConfigWebApplicationContext();
  container.addListener(new ContextLoaderListener(rootContext));
  AnnotationConfigWebApplicationContext webContext = new AnnotationConfigWebApplicationContext();
  DispatcherServlet dispatcherServlet = new DispatcherServlet(webContext);
  ServletRegistration.Dynamic dispatcher = container.addServlet("dispatcher", dispatcherServlet);

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 {
 protected Class<?>[] getRootConfigClasses() {
  return new Class<?>[]{RootConfiguration.class};

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

 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: