• springboot mvc自动配置(二)注册DispatcherServlet到ServletContext


    所有文章

    https://www.cnblogs.com/lay2017/p/11775787.html

    正文

    上一篇文章中,我们看到了DispatcherServlet和DispatcherServletRegistrationBean这两个Bean的自动配置。DispatcherServlet我们很熟悉,DispatcherServletRegistrationBean负责将DispatcherServlet注册到ServletContext当中。

    DispatcherServletRegistrationBean的类图

    既然该类的职责是负责注册DispatcherServlet,那么我们得知道什么时候触发注册操作。为此,我们先看看DispatcherServletRegistrationBean这个类的类图

    注册DispatcherServlet流程

    ServletContextInitializer

    我们看到,最上面是一个ServletContextInitializer接口。我们可以知道,实现该接口意味着是用来初始化ServletContext的。我们看看该接口

    public interface ServletContextInitializer {
        void onStartup(ServletContext servletContext) throws ServletException;
    }

    RegistrationBean

    看看RegistrationBean是怎么实现onStartup方法的

    @Override
    public final void onStartup(ServletContext servletContext) throws ServletException {
        String description = getDescription();
        if (!isEnabled()) {
            logger.info(StringUtils.capitalize(description) + " was not registered (disabled)");
            return;
        }
        
        register(description, servletContext);
    }        

    调用了内部register方法,跟进它

    protected abstract void register(String description, ServletContext servletContext);

    这是一个抽象方法

    DynamicRegistrationBean

    再看DynamicRegistrationBean是怎么实现register方法的

    @Override
    protected final void register(String description, ServletContext servletContext) {
        D registration = addRegistration(description, servletContext);
        if (registration == null) {
            logger.info(StringUtils.capitalize(description) + " was not registered (possibly already registered?)");
            return;
        }
        configure(registration);
    }

    跟进addRegistration方法

    protected abstract D addRegistration(String description, ServletContext servletContext);

    一样是一个抽象方法

    ServletRegistrationBean

    再看ServletRegistrationBean是怎么实现addRegistration方法的

    @Override
    protected ServletRegistration.Dynamic addRegistration(String description, ServletContext servletContext) {
        String name = getServletName();
        return servletContext.addServlet(name, this.servlet);
    }

    我们看到,这里直接将DispatcherServlet给add到了servletContext当中。

    总结

    总的来说,其实就是触发了初始化ServletContext时候的回调接口onStartup方法,而后直接将DispatcherServlet作为一个Servlet给add到ServletContext当中。

  • 相关阅读:
    机房收费系统重构(三)—工厂+反射+DAL
    机房收费系统重构(二)—菜鸟入门
    机房收费系统重构(—)—小试牛刀
    vb.net机房收费登录功能
    设计模式总结之结构型模式
    设计模式总结之创建型模式
    大话设计之桥接模式
    大话设计之单例模式
    大话设计之适配器模式
    大话设计之抽象工厂模式
  • 原文地址:https://www.cnblogs.com/lay2017/p/11804631.html
Copyright © 2020-2023  润新知