继承HttpServlet 类,该类实现了servlet接口,根据servlet的生命周期,web容器启动时会调用init()方法。请求进来时会调用service()方法。
一.DispathServlet 的初始化。
Init()方法分析:
- HttpServletBean中实现了init(),其中调用了initServletBean()方法。
- FrameworkServlet中重写了initServletBean()方法,在该方法中有初始化web容器的操作initWebApplicationContext()如下。
InitWebApplicationContext()内部做了两个很重要的事情:一个是创建web的spring容器,一个是初始化springmvc的组件。
1)createWebApplicationContext()方法创建web容器。如下:
createWebApplicationContext()内部的操作:
//创建容器
ConfigurableWebApplicationContext wac=
(ConfigurableWebApplicationContext) BeanUtils.instantiateClass(contextClass);
//设置环境变量
wac.setEnvironment(getEnvironment());
//设置父容器
wac.setParent(parent);
//搞什么的?没搞明白
wac.setConfigLocation(getContextConfigLocation());
//配置并刷新容器
configureAndRefreshWebApplicationContext(wac);
return wac;
在configureAndRefreshWebApplicationContext()方法内部,做了属性的设置,如ServletConfig,NameSpace,Listener,初始化Environment,最重要的是调用了容器的refresh()方法。如下:
到这里,web容器就创建好了。
- 初始化springMVC的组件。回到FrameworkServlet ,initWebApplicationContext()方法中调用onRefresh()方法,如下:
子类DispatcherServlet中重写了onRefresh()方法。在方法内部调用了initStrategies()
再来看一下initStrategies内部,初始化springMVC的各个组建,如下:
这里面的初始化,都大同小异了,都是去前面创建的容器中拿bean然后把bean赋值给DispatchServlet的变量。