1、ContextLoaderListener 监听器
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());
}
}
1、创建容器对象
this.context = this.createWebApplicationContext(servletContext);
//查找需要使用的容器类,默认从 contextClass 属性获取,没有该属性,从 ContextLoader.properties 文件中进行读取,采用的是 XmlWebApplicationContext 容器
Class<?> contextClass = this.determineContextClass(sc);
return (ConfigurableWebApplicationContext)BeanUtils.instantiateClass(contextClass);
2、刷新容器
this.configureAndRefreshWebApplicationContext(cwac, servletContext);
//1.将 ServletContext 放到容器中
wac.setServletContext(sc);
//2.读取 contextConfigLocation 配置文件路径
configLocationParam = sc.getInitParameter("contextConfigLocation");
//3.刷新容器
wac.refresh();
3、设置属性到 ServletContext
//属性名称为 WebApplicationContext.class.getName() + ".ROOT";
servletContext.setAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, this.context);
2、DispatcherServlet 组件
1、该组件最终是一个 Servlet,所以会执行一次 init 方法, 并在业务调用时执行多次 service,init 在 HttpServletBean 中
public final void init() throws ServletException {
//...省略
initServletBean();
}
2、initServletBean,在 FrameworkServlet 中实现
protected final void initServletBean() throws ServletException {
this.webApplicationContext = initWebApplicationContext();
//空实现
initFrameworkServlet();
}
//init实现
WebApplicationContext rootContext =
WebApplicationContextUtils.getWebApplicationContext(getServletContext());
WebApplicationContext wac = null;
//1.使用的是 XmlWebApplicationContext 容器
wac = createWebApplicationContext(rootContext);
//2.该方法在 DispatcherServlet 中重写,用来初始化 Dispatcher 的相关组件
onRefresh()