0%

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

启动方式

jar包启动

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

1
2
3
4
5
6
7
8
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>

jar包目录结构

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
example.jar
|
+-META-INF
| +-MANIFEST.MF
+-org
| +-springframework
| +-boot
| +-loader
| +-<spring boot loader classes>
+-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节点下指定项目名如 <finalName>springboot-demo</finalName>
  3. 更改启动类如下:
1
2
3
4
5
6
7
8
9
10
11
12
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工厂实例、初始化监听器

1
2
3
public SpringApplication(Class<?>... primarySources) {
this(null, primarySources);
}
1
2
3
4
5
6
7
8
9
10
11
12
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

1
2
3
4
5
6
7
8
9
10
11
12
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中看到

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
private <T> Collection<T> getSpringFactoriesInstances(Class<T> type,Class<?>[] parameterTypes, Object... args) {
ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
// Use names and ensure unique to protect against duplicates
Set<String> names = new LinkedHashSet<>(
SpringFactoriesLoader.loadFactoryNames(type, classLoader));
List<T> instances = createSpringFactoriesInstances(type, parameterTypes,classLoader, args, names);
AnnotationAwareOrderComparator.sort(instances);
return instances;
}

private <T> List<T> createSpringFactoriesInstances(Class<T> type, Class<?>[] parameterTypes, ClassLoader classLoader, Object[] args, Set<String> names) {
List<T> 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 字符串的栈元素来取得应用的启动类。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
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)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
public ConfigurableApplicationContext run(String... args) {
StopWatch stopWatch = new StopWatch();
stopWatch.start();
ConfigurableApplicationContext context = null;
Collection<SpringBootExceptionReporter> 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容器

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

鼓励一下~