众所周之,spring源码解析之默认配置文件名/WEB-INF/applicationContext.xml。但是这个是在spring源代码里记录的呢?
今天就抱着试一试的态度去找到答案。
首先查看工程中的 web.xml,其中配置 spring的代码如下
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/applicationContext.xml</param-value>
<description>Spring配置文件初始化WebApplicationContext</description>
<contextClass></contextClass> <!-- 自定义 -->
</context-param>
<!-- spring 配置 对应的是 [org.springframework.web] 属于spring-web JAR包 applicationContext.xml 汇总多个 配置文件-->
<!-- spring 装载器 -->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
其中 参数名 contextConfigLocation 就是描述spring配置文件初始化的位置。
那咱们就从 spring 装载器 listener-class 的 ContextLoaderListener.java 查询结果
这里有 spring-web.jar的源码查看地址:其中描述了需要通过 ContextLoader.java 来初始化 webApplicationContext对象
public void contextInitialized(ServletContextEvent event) {
this.contextLoader = createContextLoader();
if (this.contextLoader == null) {
this.contextLoader = this;
}
this.contextLoader.initWebApplicationContext(event.getServletContext());
}
jar包中 包含对应的配置文件 ContextLoader.properties 文件
org.springframework.web.context.WebApplicationContext=org.springframework.web.context.support.XmlWebApplicationContext
那么好吧,我们将在 XmlWebApplicationContext.java 文件中找到我们想要的答案!
获取默认配置文件名:
protected String[] getDefaultConfigLocations()
{
if(getNamespace() != null)
return (new String[] {
(new StringBuilder("/WEB-INF/")).append(getNamespace()).append(".xml").toString()
});
else
return (new String[] {
"/WEB-INF/applicationContext.xml"
});
}
如果为null,没有指定文件名的话,那么就是默认的
/applicationContext.xml