前文回顾
现在我们知道,ContextLoaderListener会初始化根容器,
web.xml中配置
<servlet>
<servlet-name>appServlet</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>
classpath:webmvc-basic-webapp.xml,
classpath:webmvc-config.xml
</param-value>
</init-param>
<load-on-startup>2</load-on-startup>
</servlet>
则会启动继承父容器的一个自容器,具体过程
初始化 org.springframework.web.servlet.DispatcherServlet
继承关系如下
可以看到DispatcherServlet 是一个标准的servlet
初始化过程如下
如果 Servlet 的 load-on-startup 配置项大于 0,那么在 Context 容器启动的时候就会被实例化
DispatcherServlet
随web容器初始化,执行 init()
方法,这个方法定义在 父类 HttpServletBean
上
@Override
public final void init() throws ServletException {
if (logger.isDebugEnabled()) {
logger.debug("Initializing servlet '" + getServletName() + "'");
}
// Set bean properties from init parameters.
try {
//ServletConfigPropertyValues是个静态类,从ServletConfig读取初始化配置并且存储
PropertyValues pvs = new ServletConfigPropertyValues(getServletConfig(), this.requiredProperties);
//BeanWrapper 具有转换设置java bean属性的能力,具体可参数属性编辑器一章
BeanWrapper bw = PropertyAccessorFactory.forBeanPropertyAccess(this);
ResourceLoader resourceLoader = new ServletContextResourceLoader(getServletContext());
//注册了Resource类型的属性编辑器
bw.registerCustomEditor(Resource.class, new ResourceEditor(resourceLoader, getEnvironment()));
//初始化,默认情况下没有做任何事
initBeanWrapper(bw);
//设置DispatcherServlet 各种属性
bw.setPropertyValues(pvs, true);
}
catch (BeansException ex) {
if (logger.isErrorEnabled()) {
logger.error("Failed to set bean properties on servlet '" + getServletName() + "'", ex);
}
throw ex;
}
// Let subclasses do whatever initialization they like.
initServletBean();
if (logger.isDebugEnabled()) {
logger.debug("Servlet '" + getServletName() + "' configured successfully");
}
}
可以看到这个方法的主要的逻辑是,读取web环境的配置的参数并且存储起来,然后调用initServletBean
继续初始化,initServletBean
这个方法定义在子类org.springframework.web.servlet.FrameworkServlet
中,核心逻辑为
try {
this.webApplicationContext = initWebApplicationContext();
initFrameworkServlet();
}
可以看出是在初始化bean容器
initWebApplicationContext
初始化上下文
protected WebApplicationContext initWebApplicationContext() {
//获取根上下文
WebApplicationContext rootContext =
WebApplicationContextUtils.getWebApplicationContext(getServletContext());
WebApplicationContext wac = null;
//DispatcherServlet 中存在一个webApplicationContext为参数的构造函数,这个部分是当webApplicationContext 被设置的情况下调用
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
cwac.setParent(rootContext);
}
configureAndRefreshWebApplicationContext(cwac);
}
}
}
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
//在 ServletContext 中寻找 contextAttribute 为 key的属性,一般不会找到,返回null
wac = findWebApplicationContext();
}
if (wac == null) {
// No context instance is defined for this servlet -> create a local one
//创建 WebApplicationContext ,并且设置根上下文为父上下文,ServletConfig,SevletContext等实例配置到这个山下文中
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.
//刷新 这个方法 在 DispatcherServlet 被重新定义
onRefresh(wac);
}
if (this.publishContext) {
// Publish the context as a servlet context attribute.
String attrName = getServletContextAttributeName();
//将新创建的 WebApplicationContext放到ServletContext中
getServletContext().setAttribute(attrName, wac);
if (this.logger.isDebugEnabled()) {
this.logger.debug("Published WebApplicationContext of servlet '" + getServletName() +
"' as ServletContext attribute with name [" + attrName + "]");
}
}
return wac;
}
这段代码很熟悉,和(1)中初始化bean容器的代码很详细,不同的是这里父容器是必有的,也就是上一步初始化的根容器
最后在DispatcherServlet
中执行onRefresh完成初始化,可以看到是各种策略的初始化
@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);
}
根据函数名称不难看出每个方法具体的功能,
附:
开启<mvc:annotation-driven/>,
将会初始化两个bean。RequestMappingHandlerMapping
和RequestMappingHandlerAdapter
大致介绍下,RequestMappingHandlerMapping
初始化后会读取并分析保存所有的@RequestMapping
注解的方法,并提供接口根据HttpSevletRequest得到对应的方法
RequestMappingHandlerAdapter
则保存了参数格式解释与绑定,返回值解析,等相关的策略,获取匹配的方法后使用具体执行方法
用于分配请求和执行结果,这两个Bean的的初始化在4 中说明
这两个bean分别在initHandlerMappings
,initHandlerAdapters
l两个方法给放到DispatcherServlet.handlerMappings
和DispatcherServlet.handlerAdapters
中
至此,两个bean容器均初始化完成,需要注意的是因为aop配置是针对bean容器配置的,所以aop配置一定要在对应的bean容器下配置才能生效