关于springmvc核心控制器DispatcherServlet的个人心得

一、DispatcherServlet的源码分析
关于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
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值