How To Use Spring WebInitializer
How To Use Spring WebInitializer
The DispatcherServlet has always served as the doorway component or front controller in a Spring
Framework Web MVC application. Its job has been and still is to marshal requests to other
components in the Spring MVC application backend and to orchestrate a response back to clients.
1 <servlet>
2 <servlet-name>dispatcher</servlet-name>
3 <servlet-class>org.springframework.web.servlet.DispatcherServlet
4 </servlet-class>
5 </servlet>
6 <servlet-mapping>
7 <servlet-name>dispatcher</servlet-name>
8 <url-pattern>*.request</url-pattern>
9 </servlet-mapping>
With the presence of the Servlet 3.0 specification, the web.xml file in a Web application is now
optional. The Servlet 3.0 API brought annotations to the Java Web application world allowing the
registration of servlets to be accomplished by annotation.
However, since you dont write the DispatcherServlet, and the Spring community didnt have the
knowledge and details of your application to be able to annotate the DispatcherServlet for you, there
was a bit of a quandary. How do you get the DispatcherServlet registered with the Web container
without web.xml?
The WebApplicationInitializer
The answer was provided in Spring 3.1 (and of course is available with Spring 4 which came out in
December 2013) with the WebApplicationInitializer. An implementation of the
WebApplicationInitializer interface configures the ServletContext programmatically. In particular, it
allows for the creation, configuration, and registration of the DispatcherServlet
programmatically. Thereby allowing the web.xml file to be removed from modern Spring MVC
applications. A simple implementation of WebApplicationInitializer is shown below.
When you need to customize the associated WebApplicationContext (i.e. the Spring container), you
may prefer to build an instance of the Spring container in the WebApplicationInitializer and provide
the container to the DispatcherServlet.
Wrap Up
With the WebApplicationInitializer, Spring Framework Web MVC applications can now rid
themselves of web.xml. Additional configuration/implementations are available for programmatically
registering the DispatcherServlet and configuring the Spring container see here for more details.
If you would like to learn more about the Spring Framework or Spring Framework Web MVC, I
encourage you to take a look at Intertechs line of Spring Framework training classes. I just
completed updating our Spring classes to Spring Framework 4. There are a lot of new features in
later versions of Spring 3 and now Spring 4. Some of them have been covered in recent blog posts
(see generics, meta annotations, conditional bean configuration, and ordering autowired
collections ), but you can learn more about them in our new classes.