SpringMVC启动过程中如果你有认真观察的话,你会发现控制台将地址映射的信息打印一遍,并且提醒你,系统已经启动完毕。如果此时你的系统又再次打印了一遍地址映射的信息,并再次提醒你系统启动关闭,那你可就要注意了,你可能存在着地址映射两次的问题。
首先我们来看一段XML来分析一下,为什么会有这个问题的存在。
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:applicationContext*.xml</param-value>
</context-param>
上面这个配置有没有很眼熟,如果没有看过的话,你Spring还没学吧,小伙子。。。。
大家是不是都习惯性的命名,然后通过扫描一遍扫进去,比如说我:
applicationContext.xml
applicationContext-shiro.xml
applicationContext-redis.xml
applicationContext-servlet.xml
首先我们的ContextLoaderListener会根据contextConfigLocation的配置信息去查找相关的配置文件来启动Sping容器,很幸运的是我们配置的值为classpath:applicationContext*.xml,这个配置意味着我们在classpath下配置的所有的配置文件都将会被扫描到Spring容器中(PS:classpath没什么好解释了的吧)。紧接着,所有的配置文件全部被加载成功了,包括SpringMVC在内的applicationContext-servlet.xml配置文件,Spring容器启动完毕了,此时SpringMVC的地址第一次被映射。
<servlet>
<servlet-name>spring</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:applicationContext-servlet.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
启动完毕了以后,系统还发现你在web.xml中配置了如上信息,你的这个配置,就相当于告诉系统,我要开启SpringMVC功能,DispatcherServlet会根据contextConfigLocation的配置进行加载SpringMVC的相关配置信息,此时SpringMVC的地址第二次被映射。
原因很简单,其实就是Spring容器ContextLoaderListener加载了一遍,DispatcherServlet紧接着又加载了一遍, 这就是为什么会映射两遍的原因,解决方案很简单,就是把你的强迫症改掉,把SpringMVC的配置文件的名字改掉,不再被ContextLoaderListener的contextConfigLocation所匹配到就可以了。