springmvc
org.springframework.web.servlet.DispatcherServlet
contextConfigLocation
classpath:springmvc-config.xml
1
springmvc
/
上面是在web.xml配置文件中加载springmvc配置文件生成webapplicationcontext容器的经典配置。
我们可以看到,在web应用一启动,该DispatcherServlet就被加载了,加载的时候提供了contextConfigLoacation的初始值,然后通过类的全限定类名使用反射加载该类。
/*** Set the context config location explicitly, instead of relying on the default
* location built from the namespace. This location string can consist of
* multiple locations separated by any number of commas and spaces.*/
public voidsetContextConfigLocation(String contextConfigLocation) {this.contextConfigLocation =contextConfigLocation;
}
以上代码是在DispatcherSevlet父类FrameworkServlet中,可以看到提供contextConfigloaction后该类就有了srpingmvc配置文件路径。
protectedWebApplicationContext createWebApplicationContext(ApplicationContext parent) {
Class> contextClass =getContextClass();if (this.logger.isDebugEnabled()) {this.logger.debug("Servlet with name '" + getServletName() +
"' will try to create custom WebApplicationContext context of class '" +contextClass.getName()+ "'" + ", using parent context [" + parent + "]");
}if (!ConfigurableWebApplicationContext.class.isAssignableFrom(contextClass)) {throw newApplicationContextException("Fatal initialization error in servlet with name '" + getServletName() +
"': custom WebApplicationContext class [" + contextClass.getName() +
"] is not of type ConfigurableWebApplicationContext");
}
ConfigurableWebApplicationContext wac=(ConfigurableWebApplicationContext) BeanUtils.instantiateClass(contextClass);
wac.setEnvironment(getEnvironment());
wac.setParent(parent);
wac.setConfigLocation(getContextConfigLocation());
configureAndRefreshWebApplicationContext(wac);returnwac;
}
以上代码是DispatcherSevlet父类FrameworkServlet中的创造webapplicationcontext的方法,在方法中可以看到获得刚刚设置的springmvc配置文件的路径,并且set到ConfigurableWebApplicationContext用于创建容器。
大体流程就是这样,现在做下小总结:
当web应用启动的时候配置在web.xml中的DisPartcherServlet就被加载,怎么被加载的呢?
通过提供该类的全限定类名和初始化参数使用反射加载。加载后生成了webApplicationContext容器,
通过该容器就可以使用ioc、aop等spring功能了。需要说明的是该容器的生成需要sevlectContext,
因此必须得再拥有web容器的前提下才能加载webApplicationContext容器。因此,即使它继承自
applicationContext,因此它的初始化方式也与applicationContext和BeanFactory不同