解决SpringMVC启动过程当中地址映射两遍布任务两次启动问题

SpringMVC启动过程当中若是你有认真观察的话,你会发现控制台将地址映射的信息打印一遍,而且提醒你,系统已经启动完毕。若是此时你的系统又再次打印了一遍地址映射的信息,并再次提醒你系统启动关闭,那你可就要注意了,你可能存在着地址映射两次的问题。web

 

首先咱们来看一段XML来分析一下,为何会有这个问题的存在。redis

<context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>classpath:applicationContext*.xml</param-value> 
</context-param>

上面这个配置有没有很眼熟,若是没有看过的话,你Spring还没学吧,小伙子。。。。spring

 

你们是否是都习惯性的命名,而后经过扫描一遍扫进去,好比说我:app

applicationContext.xmlspa

applicationContext-shiro.xmlcode

applicationContext-redis.xmlxml

applicationContext-servlet.xmlservlet

 

首先咱们的ContextLoaderListener会根据contextConfigLocation的配置信息去查找相关的配置文件来启动Sping容器,很幸运的是咱们配置的值为classpath:applicationContext*.xml,这个配置意味着咱们在classpath下配置的全部的配置文件都将会被扫描到Spring容器中(PS:classpath没什么好解释了的吧)。紧接着,全部的配置文件所有被加载成功了,包括SpringMVC在内的applicationContext-servlet.xml配置文件,Spring容器启动完毕了,此时SpringMVC的地址第一次被映射。it

 

<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的地址第二次被映射。io

 

缘由很简单,其实就是Spring容器ContextLoaderListener加载了一遍,DispatcherServlet紧接着又加载了一遍, 这就是为何会映射两遍的缘由,解决方案很简单,就是把你的强迫症改掉,把SpringMVC的配置文件的名字改掉,再也不被ContextLoaderListener的contextConfigLocation所匹配到就能够了。