spring-boot下web服務啓動

web服務啓動執行順序:
1、判斷是否指定了動態參數如:-Dspring.profiles.active=dev,加載application-dev.properties文件等,
2、判斷是否是web環境,加載xml文件
3、啓動web服務器
4、加載屬性配置文件
5、掃描實體進行註冊
6、指定服務端口號

啓動Spring-boot時:
1、先通過一個簡單的查找Servlet的類的方式來判斷是否是web環境

private static final String[] WEB_ENVIRONMENT_CLASSES = { "javax.servlet.Servlet",
    "org.springframework.web.context.ConfigurableWebApplicationContext" };

private boolean deduceWebEnvironment() {
    for (String className : WEB_ENVIRONMENT_CLASSES) {
        if (!ClassUtils.isPresent(className, null)) {
            return false;
        }
    }
    return true;
}

如果是web環境:
則創建AnnotationConfigEmbeddedWebApplicationContext類,進行初始化xml文件,
否則創建AnnotationConfigApplicationContext類

    //org.springframework.boot.SpringApplication
    protected ConfigurableApplicationContext createApplicationContext() {
        Class<?> contextClass = this.applicationContextClass;
        if (contextClass == null) {
            try {
                contextClass = Class.forName(this.webEnvironment
                        ? DEFAULT_WEB_CONTEXT_CLASS : DEFAULT_CONTEXT_CLASS);
            }
            catch (ClassNotFoundException ex) {
                throw new IllegalStateException(
                        "Unable create a default ApplicationContext, "
                                + "please specify an ApplicationContextClass",
                        ex);
            }
        }
        return (ConfigurableApplicationContext) BeanUtils.instantiate(contextClass);
    }

2、獲取EmbeddedServletContainerFactory的實現類
spring boot通過獲取EmbeddedServletContainerFactory來啓動對應的web服務器。
常用的兩個實現類是TomcatEmbeddedServletContainerFactory、JettyEmbeddedServletContainerFactory
啓動tomcat的代碼:

//TomcatEmbeddedServletContainerFactory
@Override
public EmbeddedServletContainer getEmbeddedServletContainer(
        ServletContextInitializer... initializers) {
    Tomcat tomcat = new Tomcat();
    File baseDir = (this.baseDirectory != null ? this.baseDirectory
            : createTempDir("tomcat"));
    tomcat.setBaseDir(baseDir.getAbsolutePath());
    Connector connector = new Connector(this.protocol);
    tomcat.getService().addConnector(connector);
    customizeConnector(connector);
    tomcat.setConnector(connector);
    tomcat.getHost().setAutoDeploy(false);
    tomcat.getEngine().setBackgroundProcessorDelay(-1);
    for (Connector additionalConnector : this.additionalTomcatConnectors) {
        tomcat.getService().addConnector(additionalConnector);
    }
    prepareContext(tomcat.getHost(), initializers);
    return getTomcatEmbeddedServletContainer(tomcat);
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章