Web容器构造DispatcherServlet完成之后,调用Servlet的init方法
public void init(ServletConfig config) throws ServletException {
this.config = config;
this.init();
}
这个方法将Web容器传入的ServletConfig赋予config属性,并调用子类HttpServletBean的init方法.
@Override
public final void init() throws ServletException {
...
// Set bean properties from init parameters.
//通过servletConfig对象获取初始化参数,并封装成一个PropertyValue,并对必要的属性进行校验,如果没有则抛出异常
PropertyValues pvs = new ServletConfigPropertyValues(getServletConfig(), this.requiredProperties);
BeanWrapper bw = PropertyAccessorFactory.forBeanPropertyAccess(this);//bw可以反射的方式对this进行属性赋值
ResourceLoader resourceLoader = new ServletContextResourceLoader(getServletContext());
bw.registerCustomEditor(Resource.class, new ResourceEditor(resourceLoader, getEnvironment()));
initBeanWrapper(bw);
bw.setPropertyValues(pvs, true);//对传入的bean进行属性赋值
...
// Let subclasses do whatever initialization they like.
initServletBean();
}
子类FrameworkServlet对initServletBean方法进行实现,主要是初始化servlet的WebApplicationContext;
try {
this.webApplicationContext = initWebApplicationContext();
initFrameworkServlet();
}
protected WebApplicationContext initWebApplicationContext() {
WebApplicationContext rootContext =//获取Spring在ServletContext中存放的WebApplicationContext
WebApplicationContextUtils.getWebApplicationContext(getServletContext());
WebApplicationContext wac = null;
...//判定为null,不走省略掉的代码
if (wac == null) {
wac = findWebApplicationContext();//没有获取到,为空
}
if (wac == null) {
// No context instance is defined for this servlet -> create a local one
wac = createWebApplicationContext(rootContext);//真正创建属于Servlet的WebApplicationContext
}
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方法,对Servlet进行初始化操作。
onRefresh(wac);
}
if (this.publishContext) {
// Publish the context as a servlet context attribute.
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;
}
创建一个全新的WebApplicationContext;
protected WebApplicationContext createWebApplicationContext(ApplicationContext parent) {
Class<?> contextClass = getContextClass();//获取默认的ContextClass,还是XmlWebApplicationContext
...//判定....
ConfigurableWebApplicationContext wac =
(ConfigurableWebApplicationContext) BeanUtils.instantiateClass(contextClass);
wac.setEnvironment(getEnvironment());
wac.setParent(parent);//将Spring的webApplicationContext作为它的父。
wac.setConfigLocation(getContextConfigLocation());
configureAndRefreshWebApplicationContext(wac);//根据wac的配置进行refresh操作。
return wac;
}
执行完后回到最初的方法中,接着调用initFrameworkServlet,这个方法并没有被DispatcherServlet实现。