美文网首页我爱编程
web.xml为什么会有两个spring的配置文件

web.xml为什么会有两个spring的配置文件

作者: ifeelok0319 | 来源:发表于2017-07-10 13:57 被阅读645次

问题描述

今天在看项目的时候发现项目中web.xml有两个spring的配置文件。

<!-- 第一个 -->
<context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>classpath*:spring/appcontext-*.xml</param-value>
</context-param>

<!-- 第二个 -->
<servlet>
    <servlet-name>appServlet</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <init-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>classpath:spring/appServlet-servlet.xml</param-value>
    </init-param>
    <load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
    <servlet-name>appServlet</servlet-name>
    <url-pattern>/</url-pattern>
</servlet-mapping>

不知道为什么会出现这种情况,于是在网上搜了一下。

参考文献:

正文

springmvc这个框架中,一般spring默认存在两个配置文件,一个是applicationContext.xml,另一个是spring-servlet.xml。一般情况下,我们会把注解中的自动加载,定时器的自动加载等内容写在spring-servlet.xml。然后把spring-servlet.xml,放在web.xml文件下的servlet中进行初始化。例如:

<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:spring-servlet.xml</param-value>
    </init-param>
</servlet>

而将applicationContext.xml配置成全局的形式,例如:

<context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>
        classpath:applicationContext.xml,
        classpath:spring-servlet.xml
    </param-value>
</context-param>

spring框架在加载web配置文件的时候。首先加载的是context-param配置的内容,而并不会去初始化servlet。只有进行了网站的跳转,经过了DispatcherServlet的导航的时候,才会初始化servlet,从而加载init-param中的内容。

相关文章

网友评论

    本文标题:web.xml为什么会有两个spring的配置文件

    本文链接:https://www.haomeiwen.com/subject/hvwyhxtx.html