读spring mvc 源码

試著忘記壹切 提交于 2020-01-09 10:49:16

先看看关键servlet:DispatcherServlet的继承结构图

 

 我们先从GenericServlet这个类看起。

1.这个类实现了servlet接口

2.看关键代码

 public void init(ServletConfig config) throws ServletException {
        this.config = config;
        this.init();
    }

    public void init() throws ServletException {
    }

 这里init(ServletConfig config)是实现servlet的方法,init()是新建的方法。

  而由于实现的方法里面,调用了init()这个方法,所以后续继承了GenericServlet 这个类的类,只要重写init()方法,即可对servlet的初始化部分进行修改。

 

我们再来看HttpServletBean这个类。

1.看关键代码

public final void init() throws ServletException {
        if (this.logger.isDebugEnabled()) {
            this.logger.debug("Initializing servlet '" + this.getServletName() + "'");
        }

        try {
            PropertyValues pvs = new HttpServletBean.ServletConfigPropertyValues(this.getServletConfig(), this.requiredProperties);
            BeanWrapper bw = PropertyAccessorFactory.forBeanPropertyAccess(this);
            ResourceLoader resourceLoader = new ServletContextResourceLoader(this.getServletContext());
            bw.registerCustomEditor(Resource.class, new ResourceEditor(resourceLoader, this.getEnvironment()));
            this.initBeanWrapper(bw);
            bw.setPropertyValues(pvs, true);
        } catch (BeansException var4) {
            this.logger.error("Failed to set bean properties on servlet '" + this.getServletName() + "'", var4);
            throw var4;
        }

        this.initServletBean();
        if (this.logger.isDebugEnabled()) {
            this.logger.debug("Servlet '" + this.getServletName() + "' configured successfully");
        }

    }

 这里用final修饰了init()方法(表示方法不可以被重写),那么继承了当前类的servlet,初始化的时候,必须调用这里的init()方法。也就是说,DispatcherServlet初始化的时候,是调用这个方法进行初始化的。

 

  

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!