1.SpringMvc的加载
在看文章之前,请对着代码一起看,过程一步步流程其实很简单,嘻嘻
在web.xml配置:
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
解释:配置listen的目的主要是在servlet启动的时候,会调用监听启动消息,将servlet上下文初始化到WebApplictionContext容器
而该类继承于 类ContextLoader,在初始化调用:
@Override
public void contextInitialized(ServletContextEvent event) {
initWebApplicationContext(event.getServletContext());
}
这个时候会调用 initWebApplicationContext方法,初始化默认生成XmlWebApplicationContext,一个Spring的容器,接下来看这个容器是怎么生成,并且如何初始化容器的
public WebApplicationContext initWebApplicationContext(ServletContext servletContext) {
//首先校验servlet容器是否已经初始化了spring容器
if (servletContext.getAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE) != null) {
throw new IllegalStateException(
"Cannot initialize context because there is already a root application context present - " +
"check whether you have multiple ContextLoader* definitions in your web.xml!");
}
Log logger = LogFactory.getLog(ContextLoader.class);
servletContext.log("Initializing Spring root WebApplicationContext");
if (logger.isInfoEnabled()) {
logger.info("Root WebApplicationContext: initialization started");
}
long startTime = System.currentTimeMillis();
try {
// Store context in local instance variable, to guarantee that
// it is available on ServletContext shutdown.
if (this.context == null) {
//如果spring容器没有初始化,会创建一个空的容器,这里回头看下这里的是如何获取的
this.context = createWebApplicationContext(servletContext);
}
if (this.context instanceof ConfigurableWebApplicationContext) {
ConfigurableWebApplicationContext cwac = (ConfigurableWebApplicationContext) this.context;
if (!cwac.isActive()) {
// The context has not yet been refreshed -> provide services such as
// setting the parent context, setting the application context id, etc
if (cwac.getParent() == null) {
// The context instance was injected without an explicit parent ->
// determine parent for root web application context, if any.
//这里主要是设置一个父容器,这个跟着配置走,这里不影响流程
ApplicationContext parent = loadParentContext(servletContext);
cwac.setParent(parent);
}
//这里设置一个容器的ID名,以及初始化Spring容器,这里是重点
configureAndRefreshWebApplicationContext(cwac, servletContext);
}
}
//将spring容器的应用挂在context上下文
servletContext.setAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, this.context);
ClassLoader ccl = Thread.currentThread().getContextClassLoader();
if (ccl == ContextLoader.class.getClassLoader()) {
currentContext = this.context;
}
else if (ccl != null) {
currentContextPerThread.put(ccl, this.context);
}
if (logger.isDebugEnabled()) {
logger.debug("Published root WebApplicationContext as ServletContext attribute with name [" +
WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE + "]");
}
if (logger.isInfoEnabled()) {
long elapsedTime = System.currentTimeMillis() - startTime;
logger.info("Root WebApplicationContext: initialization completed in " + elapsedTime + " ms");
}
return this.context;
}
catch (RuntimeException ex) {
logger.error("Context initialization failed", ex);
servletContext.setAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, ex);
throw ex;
}
catch (Error err) {
logger.error("Context initialization failed", err);
servletContext.setAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, err);
throw err;
}
}
在上面的过程中其实已经标记处Spring容器生成时机以及初始化的时机,总的过程:
- Servlet容器启动,触发事件以及Listen初始化方法
- 进入initWebApplicationContext先获取空的Spring容器对象
- Spring容器初始化
- 将已经初始化的容器对象放在Servlet的上下文,为以后使用
接下来看下生成过程以及容器初始化
protected WebApplicationContext createWebApplicationContext(ServletContext sc) {
//首先根据servlet获取Spring容器的类,这里会加载该类
Class<?> contextClass = determineContextClass(sc);
if (!ConfigurableWebApplicationContext.class.isAssignableFrom(contextClass)) {
throw new ApplicationContextException("Custom context class [" + contextClass.getName() +
"] is not of type [" + ConfigurableWebApplicationContext.class.getName() + "]");
}
//利用反射调用无参构造函数,这里需要配置web.xml文件中
return (ConfigurableWebApplicationContext) BeanUtils.instantiateClass(contextClass);
}
//获取Spring容器
protected Class<?> determineContextClass(ServletContext servletContext) {
//首先从servlet容器配置中拿类名,然后加载该类
String contextClassName = servletContext.getInitParameter(CONTEXT_CLASS_PARAM);
if (contextClassName != null) {
try {
return ClassUtils.forName(contextClassName, ClassUtils.getDefaultClassLoader());
}
catch (ClassNotFoundException ex) {
throw new ApplicationContextException(
"Failed to load custom context class [" + contextClassName + "]", ex);
}
}
//如果上下文获取不到那么就会从defaultStrategies中获取,该对象读取的是ContextLoader.properties文件,里面内容配置的就是org.springframework.web.context.support.XmlWebApplicationContext
else {
contextClassName = defaultStrategies.getProperty(WebApplicationContext.class.getName());
try {
//类的加载
return ClassUtils.forName(contextClassName, ContextLoader.class.getClassLoader());
}
catch (ClassNotFoundException ex) {
throw new ApplicationContextException(
"Failed to load default context class [" + contextClassName + "]", ex);
}
}
}
总结以上,获取空Spring容器对象:
- 首先从Servlet容器是否配置该Spring容器的类的类名
- 如果在上下文配置那么加载该类返回,否则
- 使用默认文件ContextLoader.properties配置的类名进行加载
- 获取了Spring上下文类后,使用反射调用无参构造方法,生成一个空的对象
生成一个空的对象如何把我们的Spring XML文件注入进去呢?
protected void configureAndRefreshWebApplicationContext(ConfigurableWebApplicationContext wac, ServletContext sc) {
//设置Spring容器的id,这里不重要
if (ObjectUtils.identityToString(wac).equals(wac.getId())) {
// The application context id is still set to its original default value
// -> assign a more useful id based on available information
String idParam = sc.getInitParameter(CONTEXT_ID_PARAM);
if (idParam != null) {
wac.setId(idParam);
}
else {
// Generate default id...
wac.setId(ConfigurableWebApplicationContext.APPLICATION_CONTEXT_ID_PREFIX +
ObjectUtils.getDisplayString(sc.getContextPath()));
}
}
//把servlet容器放入web Spring上下文件,这个时候其实他俩已经互相引用了
wac.setServletContext(sc);
//这个就是从容器上下文获取Spring xml的路径,需要在web.xml配置
//<context-param>
// <param-name>contextConfigLocation</param-name>
// <param-value>classpath:spring/context.xml</param-value>
//</context-param>
String configLocationParam = sc.getInitParameter(CONFIG_LOCATION_PARAM);
if (configLocationParam != null) {
//将文件的路径赋值给Spring上下文容器
wac.setConfigLocation(configLocationParam);
}
// The wac environment's #initPropertySources will be called in any case when the context
// is refreshed; do it eagerly here to ensure servlet property sources are in place for
// use in any post-processing or initialization that occurs below prior to #refresh
ConfigurableEnvironment env = wac.getEnvironment();
if (env instanceof ConfigurableWebEnvironment) {
((ConfigurableWebEnvironment) env).initPropertySources(sc, null);
}
customizeContext(sc, wac);
//Spring 容器的初始化,内容就设计的Spring的内容了
wac.refresh();
}
这里初始化过程就是:
- 将Spring上下文容器以及servlet上下文容器互相引用(虽然理解这个流程是一个细节,但是功能上是很重要的)
- 从servlet容器获取Spring的路径,放入Spring容器中
- 调用Spring 容器的refresh方法初始化Spring
接下来看下Spring以及Servlet如何整合的,在web.xml会有以下配置
<servlet>
<servlet-name>springmvc</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>1</load-on-startup>
<async-supported>true</async-supported>
</servlet>
<servlet-mapping>
<servlet-name>springmvc</servlet-name>
<url-pattern>*.htm</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>springmvc</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
在配置一个Servlet,在符合mapping的url请求都会走DispatchServlet,从名字可以看到他有分发的意思,先看下他继承的接口,看下他大概起到一个什么角色
可以看到这个这个类可以获取Spring容器,但是更多的代码功能是偏向于Servlet实现的,它起到了一个Servlet和Spring的一个桥梁作用 ,我们之前只使用通过继承HttpServlet来实现我们业务功能,它的和与生命周期相关的主要是三个方法:
-
void init(ServletConfig config) throws ServletException
-
abstract void service(ServletRequest req, ServletResponse res)
-
void destroy()
涉及到Servlet生命周期的过程这里就不详细讲解,可以参考Servlet生命周期,而从类的结构开始看,从HttpServletBean继承了HttpServlet,重写了 init()方法,在里面会调用 void initServletBean()方法,而FrameworkServlet正好重写了该方法,并且调用方法WebApplicationContext initWebApplicationContext(),重点从这里开始:
protected WebApplicationContext initWebApplicationContext() {
//从前面可以看到我们可以从Servlet上下文拿到Spring加载的容器
WebApplicationContext rootContext =
WebApplicationContextUtils.getWebApplicationContext(getServletContext());
WebApplicationContext wac = null;
//初始化的时候这个逻辑是不会走的,如果构造方法注入才会走这个逻辑
if (this.webApplicationContext != null) {
// A context instance was injected at construction time -> use it
wac = this.webApplicationContext;
if (wac instanceof ConfigurableWebApplicationContext) {
ConfigurableWebApplicationContext cwac = (ConfigurableWebApplicationContext) wac;
if (!cwac.isActive()) {
// The context has not yet been refreshed -> provide services such as
// setting the parent context, setting the application context id, etc
if (cwac.getParent() == null) {
// The context instance was injected without an explicit parent -> set
// the root application context (if any; may be null) as the parent //将之前创建的加载的Spring作为当前web Spring 容器的父容器
cwac.setParent(rootContext);
}
//里面会调用refresh方法加载Spring bean
configureAndRefreshWebApplicationContext(cwac);
}
}
}
//如果构造方法没有注入,那么从servlet上下文获取
if (wac == null) {
// No context instance was injected at construction time -> see if one
// has been registered in the servlet context. If one exists, it is assumed
// that the parent context (if any) has already been set and that the
// user has performed any initialization such as setting the context id
wac = findWebApplicationContext();
}
//如果构造方法以及上下文都没有,那么就创建一个
if (wac == null) {
// No context instance is defined for this servlet -> create a local one
wac = createWebApplicationContext(rootContext);
}
if (!this.refreshEventReceived) {
// Either the context is not a ConfigurableApplicationContext with refresh
// support or the context injected at construction time had already been
// refreshed -> trigger initial onRefresh manually here.
//开始启动加载SpringMvc的配置信息,这里是重点
onRefresh(wac);
}
if (this.publishContext) {
// Publish the context as a servlet context attribute.
//将创建的Spring容器放在Servlet上下文
String attrName = getServletContextAttributeName();
getServletContext().setAttribute(attrName, wac);
if (this.logger.isDebugEnabled()) {
this.logger.debug("Published WebApplicationContext of servlet '" + getServletName() +
"' as ServletContext attribute with name [" + attrName + "]");
}
}
return wac;
}
以上其实做了一个事情,将创建或者获取web的一个Spring容器,并且将之前加载的Spring容器作为新建的容器父容器。这个地方初始化和parent的初始化区别是啥呢?对于子容器XmlWebApplicationContext重写
protected void loadBeanDefinitions(DefaultListableBeanFactory beanFactory)
会获取/WEB-INF/*xml的controller的配置文件,parent加载的是
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:spring/context.xml</param-value>
</context-param>
因为controller依赖service层,生成controller bean是需要依赖父容器的bean注入
接下来看下onRefresh(wac)方法,可以看到我们的主角DispatchServlet主角实现了这个方法:
/**
* This implementation calls {@link #initStrategies}.
*/
@Override
protected void onRefresh(ApplicationContext context) {
initStrategies(context);
}
/**
* Initialize the strategy objects that this servlet uses.
* <p>May be overridden in subclasses in order to initialize further strategy objects.
*/
protected void initStrategies(ApplicationContext context) {
initMultipartResolver(context);
initLocaleResolver(context);
initThemeResolver(context);
initHandlerMappings(context);
initHandlerAdapters(context);
initHandlerExceptionResolvers(context);
initRequestToViewNameTranslator(context);
initViewResolvers(context);
initFlashMapManager(context);
}
从上面我们可以看到,通过之前创建或者获取的Spring上下文获取bean来初始化SpringMvc几个组件,以上的过程可以总结为以下几个步奏:
- Servlet init方法初始化容器
- 获取Servlet上下文来获得之前已经加载的Root Spring容器
- 从Servlet上下文获取Servlet本身获取web Spring上下文并且设置父容器,没有则创建一个新的
- 将新创建(获取)的Spring容器来初始化DispatchServlet的处理组件
- 开始接受请求
子容器主要放置的是Controller层相关的bean,它可以访问父容器的bean,但是父容器的是访问不了子容器的内容的