springboot12-使用外置Servlet的原理

SpringBoot使用外置Servlet的原理:

jar包:执行SpringBoot主类的main方法,启动ioc容器,创建嵌入式的Servlet容器;

war包:启动服务器,服务器启动SpringBoot应用,启动ioc容器;

我们可以找到这个类:ServletInitializer

public class ServletInitializer extends SpringBootServletInitializer {

    @Override
    protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
        return application.sources(DemoOgj01Application.class);
    }

}

Servlet3.0(Spring注解版):

规则:

​ 1)、服务器启动(web应用启动)会创建当前web应用里面每个jar包里面ServletContainerInitalizer实例;

​ 2)、ServletContainerInitalizer的实现放在jar包的META-INF/services文件下,有一个名为javax.servlet.ServletContainerInitalizer的文件,内容的内容就是ServletContainerInitalizer的实现类的全类名;

​ 3)、还可以使用@HandlesTyoes,在应用启动的时候加载我们感兴趣的class;

ctrl+H 查看接口下的实现类。

流程:

1)、启动Tomcat

2)、在这个路径下:org\springframework\spring-web\5.2.4.RELEASE\spring-web-5.2.4.RELEASE.jar!\META-INF\services\javax.servlet.ServletContainerInitializer

Spring的web模块中有这个文件:org.springframework.web.SpringServletContainerInitializer

3)、SpringServletContainerInitializer将**@HandlesTypes({WebApplicationInitializer.class})标注的所有这个类型的类传入到onStarup方法的Set**;为这些WebApplicationInitializer类型的类创建实例;

4)、每个WebApplicationInitializer都调用自己的onStarup;

5)、我们又继承了SpringBootServletInitializer,实现了以下函数,相当于我们的SpringBootServletInitializer的类会被创建对象,并执行onStarup方法;

  • 下面这个这个函数会告诉SpringBootServletInitializer我们要启动的Spring的IOC容器是哪一个,然后传入到onStarup中。
public class ServletInitializer extends SpringBootServletInitializer {

    @Override
    protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
        return application.sources(DemoOgj01Application.class);
    }
	//这个函数会告诉SpringBootServletInitializer我们要启动的Spring的IOC容器是哪一个,然后传入到onStarup中。
}

6)、SpringBootServletInitializer的示例执行onStarup的时候会createRootApplicationContext,创建容器:

public void onStartup(ServletContext servletContext) throws ServletException {
        this.logger = LogFactory.getLog(this.getClass());
        WebApplicationContext rootAppContext = this.createRootApplicationContext(servletContext);
        if (rootAppContext != null) {
            servletContext.addListener(new ContextLoaderListener(rootAppContext) {
                public void contextInitialized(ServletContextEvent event) {
                }
            });
        } else {
            this.logger.debug("No ContextLoaderListener registered, as createRootApplicationContext() did not return an application context");
        }

    }

执行createRootApplicationContext

protected WebApplicationContext createRootApplicationContext(ServletContext servletContext) {
    //1、创建SpringApplicationBuilder
     SpringApplicationBuilder builder = this.createSpringApplicationBuilder();
     builder.main(this.getClass());
     ApplicationContext parent = this.getExistingRootWebApplicationContext(servletContext);
     if (parent != null) {
         this.logger.info("Root context already created (using as parent).");
		servletContext.setAttribute(
         WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, (Object)null);
         builder.initializers(new ApplicationContextInitializer[]{new 		  ParentContextApplicationContextInitializer(parent)});
        }
        builder.initializers(new ApplicationContextInitializer[]{new ServletContextApplicationContextInitializer(servletContext)});
        builder.contextClass(AnnotationConfigServletWebServerApplicationContext.class);
    	//2.调用configure方法,子类重写了这个方法,我们调用的是子类方法,将SpringBoot的主程序类传入
        builder = this.configure(builder);
        builder.listeners(new ApplicationListener[]{new SpringBootServletInitializer.WebEnvironmentPropertySourceInitializer(servletContext)});
    	//3.使用builder创建一个Spring应用
        SpringApplication application = builder.build();
        if (application.getAllSources().isEmpty() && MergedAnnotations.from(this.getClass(), SearchStrategy.TYPE_HIERARCHY).isPresent(Configuration.class)) {
            application.addPrimarySources(Collections.singleton(this.getClass()));
        }

        Assert.state(!application.getAllSources().isEmpty(), "No SpringApplication sources have been defined. Either override the configure method or add an @Configuration annotation");
        if (this.registerErrorPageFilter) {
            application.addPrimarySources(Collections.singleton(ErrorPageFilterConfiguration.class));
        }
		//4.启动Spring
        return this.run(application);
    }

7)、Spring的应用就启动了,并且创建IOC容器。

public ConfigurableApplicationContext run(String... args) {
    StopWatch stopWatch = new StopWatch();
    stopWatch.start();
    ConfigurableApplicationContext context = null;
    Collection<SpringBootExceptionReporter> exceptionReporters = new ArrayList();
    this.configureHeadlessProperty();
    SpringApplicationRunListeners listeners = this.getRunListeners(args);
    listeners.starting();

    Collection exceptionReporters;
    try {
        ApplicationArguments applicationArguments = new DefaultApplicationArguments(args);
        ConfigurableEnvironment environment = this.prepareEnvironment(listeners, applicationArguments);
        this.configureIgnoreBeanInfo(environment);
        Banner printedBanner = this.printBanner(environment);
        context = this.createApplicationContext();
        exceptionReporters = this.getSpringFactoriesInstances(SpringBootExceptionReporter.class, new Class[]{ConfigurableApplicationContext.class}, context);
        this.prepareContext(context, environment, listeners, applicationArguments, printedBanner);
        //刷新IOC容器,IOC容器初始化
        this.refreshContext(context);
        this.afterRefresh(context, applicationArguments);
        stopWatch.stop();
        if (this.logStartupInfo) {
            (new StartupInfoLogger(this.mainApplicationClass)).logStarted(this.getApplicationLog(), stopWatch);
        }

        listeners.started(context);
        this.callRunners(context, applicationArguments);
    } catch (Throwable var10) {
        this.handleRunFailure(context, var10, exceptionReporters, listeners);
        throw new IllegalStateException(var10);
    }

    try {
        listeners.running(context);
        return context;
    } catch (Throwable var9) {
        this.handleRunFailure(context, var9, exceptionReporters, (SpringApplicationRunListeners)null);
        throw new IllegalStateException(var9);
    }
}
发布了65 篇原创文章 · 获赞 29 · 访问量 6476

猜你喜欢

转载自blog.csdn.net/qq_41617848/article/details/104803740