前面介绍了XML(传统Spring配置方案)和当前流行JavaConfig配置方式(需要服务器支持Serlvet3.0+)
现在我们来看看,我们用Servlet2.5如何使用JavaConfig配置Spring
当然这种方式下的web.xml就必须存在了
那我们就用web.来替代JavaConfig版的MyApplicationInitializer.java
在Servlet2.5的环境下不能使用JavaConfig替代web.xml,所以我们区别于上一节SpringMVC:Maven构建SpringMVC简单配置(JavaConfig)配置就是剔除了MyApplicationInitializer.java取而代之的是web.xml
web.xml配置注意
- contextClass:指定加载Spring上下文的类为AnnotationConfigWebApplicationContext
- contextConfigLocation:不再是指向xml配置文件路径,而是指向JavaConfig类(类全名)
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">
<!-- 默认使用的是 XmlWebApplicationContext,如果指定contextClass将使用指定的见ContextLoaderListener.determineContextClass()-->
<context-param>
<param-name>contextClass</param-name>
<param-value>org.springframework.web.context.support.AnnotationConfigWebApplicationContext</param-value>
</context-param>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>com.xbz.mvc.initializer.RootApplicationJavaConfig</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<!-- Spring MVC DispatcherServlet -->
<servlet>
<servlet-name>DispatcherServlet</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<!-- 类似于ContextLoaderListener的参数配置 -->
<init-param>
<param-name>contextClass</param-name>
<param-value>org.springframework.web.context.support.AnnotationConfigWebApplicationContext</param-value>
</init-param>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>com.xbz.mvc.initializer.WebApplicationJavaConfig</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>DispatcherServlet</servlet-name>
<url-pattern>*.action</url-pattern>
</servlet-mapping>
</web-app>