在web.xml中定义contextConfigLocation参数,Spring会使用这个参数去加载所有逗号分隔的xml文件,如果没有这个参数,Spring默认加载web-inf/applicationContext.xml
文件。
例如:
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>
classpath*:applicationContext.xml,
classpath*:spring-security.xml
</param-value>
</context-param>
contextConfigLocation 参数的<param-value>
定义了要装入的 Spring 配置文件。
原理:利用ServletContextListener 实现
Spring 提供ServletContextListener 的一个实现类ContextLoaderListener ,该类可以作为 listener监听器使用,它会在创建时自动查找WEB-INF/
下的applicationContext.xml 文件。因此,如果只有一个配置文件,并且文件名为applicationContext.xml ,则只需在web.xml文件中增加如下代码即可:
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
如果有多个配置文件需要载入,则考虑使用<context-param>
元素来确定配置文件的文件名。由于ContextLoaderListener加载时,会查找名为contextConfigLocation的参数。因此,配置<context-param>
时参数名字应该是contextConfigLocation。
如果没有 contextConfigLocation 指定配置文件,则Spring 自动查找applicationContext.xml 配置文件。如果有 contextConfigLocation,则利用该参数确定的配置文件。该参数指定的一个字符串,Spring 的ContextLoaderListener 负责将该字符串分解成多个配置文件,逗号",
"、空格" “及分号”;
"都可作为字符串的分割符。如果既没有 applicationContext.xml 文件,也没有使用contextConfigLocation参数确定配置文件,或者contextConfigLocation确定的配置文件不存在。都将导致Spring 无法加载配置文件或无法正常创建ApplicationContext 实例。