To use code-based configuration, we just need to develop a class that implements the
org.springframework.web.WebApplicationInitializer interface. The WebApplicationInitializer
interface was introduced in Spring 3.1, and all classes implementing this interface will be automatically
detected by the org.springframework.web.SpringServletContainerInitializer class (which implements
Servlet 3's javax.servlet.ServletContainerInitializer interface), which bootstraps automatically in
any Servlet 3.0 containers.
Let's see a simple example of using code-based configuration to bootstrap the DispatcherServlet
WebApplicationContext, instead of declaring it in the web.xml file.
First, remove the following servlet and servlet mapping definition in Listing 17-65 from the web.xml
file.
Listing 17-65. Remove the Following Servlet Definition from web.xml
<servlet>
<servlet-name>appServlet</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/spring/appServlet/servlet-context.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
<multipart-config>
<max-file-size>5000000</max-file-size>
</multipart-config>
</servlet>
<servlet-mapping>
<servlet-name>appServlet</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
Second, create a class that implements the WebApplicationInitializer interface. Here we called it
MyWebAppInitializer, and its content is shown in Listing 17-66.
Listing 17-66. The MyWebAppInitializer Class
package com.apress.prospring3.ch17.web.init;
import
javax.servlet.MultipartConfigElement;
import
javax.servlet.ServletContext;
import
javax.servlet.ServletException;
import
javax.servlet.ServletRegistration;
import org.springframework.web.WebApplicationInitializer;
import org.springframework.web.context.support.XmlWebApplicationContext;
import org.springframework.web.servlet.DispatcherServlet;
public class MyWebAppInitializer implements WebApplicationInitializer {
@Override
public void onStartup(ServletContext container) throws ServletException {
XmlWebApplicationContext appContext = new XmlWebApplicationContext();
Search WWH :
Custom Search
Previous Page
Spring Framework 3 Topic Index
Next Page
Spring Framework 3 Bookmarks
Home