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当中。

 

 

posted @ 2019-11-06 13:32  __lay  阅读(1390)  评论(3编辑  收藏  举报