SpringBoot2.x(五)启动方式&启动原理

启动方式

jar包启动

需引入springboot应用maven构建插件(主要用来指定应用启动类):


    
        
            org.springframework.boot
            spring-boot-maven-plugin
        
    

 

 

jar包目录结构

example.jar
    |
    +-META-INF
    |  +-MANIFEST.MF
    +-org
    |  +-springframework
    |     +-boot
    |        +-loader
    |           +-
    +-BOOT-INF
    +-classes
    |  +-mycompany
    |     +-project
    |        +-YourClasses.class
    +-lib
    +-dependency1.jar
    +-dependency2.jar

 

 

mvn spring-boot:run

如果项目是maven目录结构,可以进入项目根目录输入 maven命令 mvn 项目名:run来启动

部署war包到tomcat9

  1. pom.xml中设置打包方式为 war
  2. pom.xmlbuild节点下指定项目名如 springboot-demo
  3. 更改启动类如下:
public class Application extends SpringBootServletInitializer {

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

    public static void main(String[] args) throws Exception {
        SpringApplication.run(XdclassApplication.class, args);
    }

}

 

 

  1. 打包:mvn install
  2. target中的 war包放入 tomcat9并启动 tomcat
  3. 访问 http://localhost:8080/springboot-demo/testEx

startup.bat闪退怎么办

如果你的OS是windows,也许你碰到过通过 startup.bat启动tomcat命令行闪退的情况。那通常是一些配置异常导致的,你可以在该文件的末尾加上一句 pause;,该命令行遇到异常时就会暂停而不会闪退,至此你可以从中发现异常点。

linux用户在 tomcat/logs/catlina.out查看tomcat启动日志

启动容器和第三方测试数据

常见的javaweb的启动容器有 tomcatjettyundertow

Jmter

Jmter是一个第三方测试容器性能的工具,有兴趣的可以参见 https://examples.javacodegeeks.com/enterprise-java/spring/tomcat-vs-jetty-vs-undertow-comparison-of-spring-boot-embedded-servlet-containers/ 自学一下。

启动原理概述

springboot应用启动大致分两步,从 SpringApplication.run(Application.class, args); 追溯到 run(new Class[] { primarySource }, args)再到 new SpringApplication(primarySources).run(args),可发现分为以下两步:

1.SpringApplication(primarySources)

此步主要为应用启动做准备,如判断应用类型(是否为web应用)、初始化spring工厂实例、初始化监听器

public SpringApplication(Class... primarySources) {
    this(null, primarySources);
}
public SpringApplication(ResourceLoader resourceLoader, Class... primarySources) {
    //null
    this.resourceLoader = resourceLoader;	
    //断言启动类不为空
    Assert.notNull(primarySources, "PrimarySources must not be null");
    this.primarySources = new LinkedHashSet<>(Arrays.asList(primarySources));
    this.webApplicationType = deduceWebApplicationType();
    setInitializers((Collection) getSpringFactoriesInstances(
        ApplicationContextInitializer.class));
    setListeners((Collection) getSpringFactoriesInstances(ApplicationListener.class));
    this.mainApplicationClass = deduceMainApplicationClass();
}

webApplicationType

private WebApplicationType deduceWebApplicationType() {
    if (ClassUtils.isPresent(REACTIVE_WEB_ENVIRONMENT_CLASS, null)
        && !ClassUtils.isPresent(MVC_WEB_ENVIRONMENT_CLASS, null)) {
        return WebApplicationType.REACTIVE;
    }
    for (String className : WEB_ENVIRONMENT_CLASSES) {
        if (!ClassUtils.isPresent(className, null)) {
            return WebApplicationType.NONE;
        }
    }
    return WebApplicationType.SERVLET;
}

 

这里会判断当前应用是否为web应用,查看 WebApplicationType可知有三种枚举类型,分别是 NONE(不是web应用)、SERVELT (需要 tomcatjettyundertow这样的servelt容器)、REACTIVE(这个跟之后涉及到的 WebFlux函数式编程有关)。

setInitializers

加载用来初始化spring容器的工厂实例。这些工厂类位于 META-INF/spring.factories中,你能在 spring-boo.jarspring-boot-devtool.jar中看到

private  Collection getSpringFactoriesInstances(Class type,Class[] parameterTypes, Object... args) {
    ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
    // Use names and ensure unique to protect against duplicates
    Set names = new LinkedHashSet<>(
        SpringFactoriesLoader.loadFactoryNames(type, classLoader));
    List instances = createSpringFactoriesInstances(type, parameterTypes,classLoader, args, names);
    AnnotationAwareOrderComparator.sort(instances);
    return instances;
}

private  List createSpringFactoriesInstances(Class type, Class[] parameterTypes, ClassLoader classLoader, Object[] args, Set names) {
    List instances = new ArrayList<>(names.size());
    for (String name : names) {
        try {
            Class instanceClass = ClassUtils.forName(name, classLoader);
            Assert.isAssignable(type, instanceClass);
            Constructor constructor = instanceClass.getDeclaredConstructor(parameterTypes);
            T instance = (T) BeanUtils.instantiateClass(constructor, args);
            instances.add(instance);
        }
        catch (Throwable ex) {
            throw new IllegalArgumentException(
                "Cannot instantiate " + type + " : " + name, ex);
        }
    }
    return instances;
}

 

 

deduceMainApplicationClass()

该方法遍历栈踪迹去找一个包含叫 main 字符串的栈元素来取得应用的启动类。

private Class deduceMainApplicationClass() {
    try {
        StackTraceElement[] stackTrace = new RuntimeException().getStackTrace();
        for (StackTraceElement stackTraceElement : stackTrace) {
            if ("main".equals(stackTraceElement.getMethodName())) {
                return Class.forName(stackTraceElement.getClassName());
            }
        }
    }
    catch (ClassNotFoundException ex) {
        // Swallow and continue
    }
    return null;
}

 

 

2.run(String... args)

public ConfigurableApplicationContext run(String... args) {
    StopWatch stopWatch = new StopWatch();
    stopWatch.start();
    ConfigurableApplicationContext context = null;
    Collection exceptionReporters = new ArrayList<>();
    configureHeadlessProperty();
    //获取运行时监听并启动
    SpringApplicationRunListeners listeners = getRunListeners(args);
    listeners.starting();
    try {
        ApplicationArguments applicationArguments = new DefaultApplicationArguments(args);
        ConfigurableEnvironment environment = prepareEnvironment(listeners,applicationArguments);
        configureIgnoreBeanInfo(environment);
        Banner printedBanner = printBanner(environment);
        context = createApplicationContext();
        exceptionReporters = getSpringFactoriesInstances(
            SpringBootExceptionReporter.class,
            new Class[] { ConfigurableApplicationContext.class }, context);
        prepareContext(context, environment, listeners, applicationArguments,
                       printedBanner);
        refreshContext(context);
        afterRefresh(context, applicationArguments);
        stopWatch.stop();
        ...

 

 

stopWatch

stopWatch主要用来计时,可以提取反映容器性能指标

printBanner

准备要打印的banner

createApplicationContext

创建spring容器

启动原理尚未明朗,有待后续学习

 

更多学习资料搜索

你可能感兴趣的:(spring,boot)