contextConfigLocation的相关问题
首先要了解 context-param和 listener
context-param和 listener我相信大家都不陌生,当然可能也有人云里雾里的,需要官方解释的可以自己去看官方文档,我说下我自己理解的(不完全正确,有错的欢迎大家纠正):
- 我们必须明白一点就是web项目是有启动顺序的 ,这点非常重要,项目不可能一上来就什么都加载;
- 具体的的启动顺序我们不深究,所以web文件相当于告诉项目,我们要启动那些,毕竟程序是傻的,我们不告诉,他们不加载的;
- context-param 可以理解为需要在启动时加载的上下文对象,即保证后面的程序可以读取 context-param里面的值;
- listener 则是规定程序启动就执行 listener-class 所规定的实例,相当于告诉程序,启动(至于是启动前,启动后,或者启动中的状态不深究)的时候,把规定的实例执行一遍;
- 下面的代码是常见的Spring启动配置
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:spring-config.xml</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
为什么 param-name的参数一定是contextConfigLocation
我相信这是大多数初学者的疑问,param-name的参数可以不是contextConfigLocation吗?
答案是“可以的”
只是需要修改spring框架源代码(好像说了废话),万物皆可改!
言归正传,我们来探究下contextConfigLocation的出处
对应的代码
public class ContextLoaderListener extends ContextLoader implements ServletContextListener {
public ContextLoaderListener() {
}
public ContextLoaderListener(WebApplicationContext context) {
super(context);
}
public void contextInitialized(ServletContextEvent event) {
this.initWebApplicationContext(event.getServletContext());
}
public void contextDestroyed(ServletContextEvent event) {
this.closeWebApplicationContext(event.getServletContext());
ContextCleanupListener.cleanupAttributes(event.getServletContext());
}
}
分析代码我们可知 ContextLoaderListener extends ContextLoader 即类ContextLoaderListener继承了ContextLoader,我们在跑到它的父类ContextLoader去看下
我们可以看到,前面param-name就是在这里规定的,所以要启动spring的话,默认的参数必须为contextConfigLocation,当然可以自己去改源代码!
换上其它框架也需要启动的话,找到框架对应的param-name 即可,一般会在文档说明!