Configuring front controller

With Spring 5.0, there are three ways to configure DispatcherServlet programmatically, by implementing or extending any of the following three classes:

  • WebAppInitializer interface
  • AbstractDispatcherServletInitializer abstract class
  • AbstractAnnotationConfigDispatcherServletInitializer abstract class

We will use the AbstractDispatcherServletInitializer class, as it is the preferred approach for applications that use Java-based Spring configuration. It is preferred because it allows us to start a servlet application context, as well as a root application context.

We need to create the following class to configure DispatcherServlet:

import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer;

public class SpringMvcWebInitializer extends AbstractAnnotationConfigDispatcherServletInitializer {

@Override
protected Class<?>[] getRootConfigClasses() {
return null;
}

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

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

The previous class code is equivalent to the web.xml file configuration that we created in the XML-based configuration section. In the preceding class, the getRootConfigClasses() method is used to specify the root application context configuration classes (or null, if not required). getServletConfigClasses() is used to specify the web application configuration classes (or null, if not required). The getServletMappings() method is used to specify the servlet mappings for the DispatcherServlet. Root config classes will be loaded first, then servlet config classes will be loaded. Root config classes will create an ApplicationContext, which will act as a parent context, whereas servlet config classes will create a WebApplicationContext, and it will act as a child context of the parent context.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset