一、DispatcherServlet的源码分析
从继承树关系可以看出DispatcherServlet继承自HttpServlet,所以这个类也满足init-service-destroy三阶段,下面就进入源码分析
1.1、关于init()源码的分析,因为DispatcherServlet继承自FrameWorkServlet;FrameWorkServlet又继承自HttpServletBean,而DispatcherServlet和FrameWorkServlet并没有覆写init()方法,所以直接调用基类HttpServletBean中的init()方法,源码如下
@Override
public final void init() throws ServletException {
if (logger.isDebugEnabled()) {
logger.debug("Initializing servlet '" + getServletName() + "'");
}
// 使用ServletConfig获取web.xml中的配置信息,然后使用静态内部类进行封装,getServletConfig()此方法来自GenericServlet
PropertyValues pvs = new ServletConfigPropertyValues(getServletConfig(), this.requiredProperties);
if (!pvs.isEmpty()) {
try {
//利用BeanWrapper 完成DispatcherServlet的构造,forBeanPropertyAccess()会对this进行充分判定然后创建BeanWrapper
BeanWrapper bw = PropertyAccessorFactory.forBeanPropertyAccess(this);
//获取servletContext后创建ResourceLoader
ResourceLoader resourceLoader = new ServletContextResourceLoader(getServletContext());
//用linkedMap以Resource.class为key,ResourceEditor为value存储后注册到BeanWrapper 中
bw.registerCustomEditor(Resource.class, new ResourceEditor(resourceLoader, getEnvironment()));
initBeanWrapper(bw);
bw.setPropertyValues(pvs, true);
}
catch (BeansException ex) {
if (logger.isErrorEnabled()) {
logger.error("Failed to set bean properties on servlet '" + getServletName() + "'", ex);
}
throw ex;
}
}
// 初始化ServletBean,此方法被FrameWorkSerlvet覆写
initServletBean();
if (logger.isDebugEnabled()) {
logger.debug("Servlet '" + getServletName() + "' configured successfully");
}
}
1.2、FrameWorkServlet中的initServletBean()方法源码
@Override
protected final void initServletBean() throws ServletException {
getServletContext().log("Initializing Spring FrameworkServlet '" + getServletName() + "'");
try {
//初始化SpringMvc中的Ioc容器
this.webApplicationContext = initWebApplicationContext();
//此方法还未实现内容
initFrameworkServlet();
}
catch (ServletException ex) {
}
catch (RuntimeException ex) {
}
}
1.3、初始化springMvc ioc容器的源码initWebApplicationContext()
protected WebApplicationContext initWebApplicationContext() {
WebApplicationContext rootContext =
WebApplicationContextUtils.getWebApplicationContext(getServletContext());
WebApplicationContext wac = null;
if (this.webApplicationContext != null) {
wac = this.webApplicationContext;
if (wac instanceof ConfigurableWebApplicationContext) {
Configu