实验步骤:
1、新建一个SpringBoot项目。
使用IntelliJ创建或者通过spring initializrstart.spring.io/ 生成。
2、打包该项目:
./gradlew build
3、在另一个空项目中
打开Project Settings ——> Modules,导入jar包。
4、回到主界面,查看/META-INF/MANIFEST.MF文件。注意最后一行代码。
Manifest-Version: 1.0
Start-Class: com.example.demo.DemoApplication
Spring-Boot-Classes: BOOT-INF/classes/
Spring-Boot-Lib: BOOT-INF/lib/
Spring-Boot-Version: 2.1.16.RELEASE
Main-Class: org.springframework.boot.loader.JarLauncher
5、打开这些项目中的JarLauncher文件。
public static void main(String[] args) throws Exception {
(new JarLauncher()).launch(args);
}
JarLauncher extends ExecutableArchiveLauncher
6、其中的main函数调用了父类的launch函数。
一直往上找,直到找到MainMethodRunner类。其中的run函数是关键。
public void run() throws Exception {
Class<?> mainClass = Thread.currentThread().getContextClassLoader().loadClass(this.mainClassName);
Method mainMethod = mainClass.getDeclaredMethod("main", String[].class);
mainMethod.invoke((Object)null, this.args);
}
此函数通过反射机制获取到main函数然后再执行。