Quantcast
Channel: all and sundry
Viewing all articles
Browse latest Browse all 250

AbstractAnnotationConfigDispatcherServletInitializer - Long and short of it

$
0
0
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.

Viewing all articles
Browse latest Browse all 250

Latest Images

Trending Articles



Latest Images