为什么SpringBoot的 jar 可以直接运行?
程序员的成长之路
共 10341字,需浏览 21分钟
·
2021-02-21 00:17
阅读本文大概需要 7 分钟。
来自:https://urlify.cn/uQvIna
org.springframework.boot
spring-boot-maven-plugin
├── META-INF
│ ├── MANIFEST.MF
│ └── maven
│ └── spring.study
│ └── executable-jar
│ ├── pom.properties
│ └── pom.xml
├── lib
│ ├── aopalliance-1.0.jar
│ ├── classmate-1.1.0.jar
│ ├── spring-boot-1.3.5.RELEASE.jar
│ ├── spring-boot-autoconfigure-1.3.5.RELEASE.jar
│ ├── ...
├── org
│ └── springframework
│ └── boot
│ └── loader
│ ├── ExecutableArchiveLauncher$1.class
│ ├── ...
└── spring
└── study
└── executablejar
└── ExecutableJarApplication.class
java -jar executable-jar-1.0-SNAPSHOT.jar
META-INF文件夹:程序入口,其中MANIFEST.MF用于描述jar包的信息 lib目录:放置第三方依赖的jar包,比如springboot的一些jar包 spring boot loader相关的代码 模块自身的代码
Manifest-Version: 1.0
Implementation-Title: executable-jar
Implementation-Version: 1.0-SNAPSHOT
Archiver-Version: Plexus Archiver
Built-By: Format
Start-Class: spring.study.executablejar.ExecutableJarApplication
Implementation-Vendor-Id: spring.study
Spring-Boot-Version: 1.3.5.RELEASE
Created-By: Apache Maven 3.2.3
Build-Jdk: 1.8.0_20
Implementation-Vendor: Pivotal Software, Inc.
Main-Class: org.springframework.boot.loader.JarLauncher
Spring Boot Loader抽象的一些类
jar:file:/Users/format/Develop/gitrepository/springboot-analysis/springboot-executable-jar/target/executable-jar-1.0-SNAPSHOT.jar!/
/Users/format/Develop/gitrepository/springboot-analysis/springboot-executable-jar/target/executable-jar-1.0-SNAPSHOT.jar
META-INF/
META-INF/MANIFEST.MF
spring/
spring/study/
....
spring/study/executablejar/ExecutableJarApplication.class
lib/spring-boot-starter-1.3.5.RELEASE.jar
lib/spring-boot-1.3.5.RELEASE.jar
...
jar:file:/Users/Format/Develop/gitrepository/springboot-analysis/springboot-executable-jar/target/executable-jar-1.0-SNAPSHOT.jar!/lib/spring-boot-starter-web-1.3.5.RELEASE.jar!/
jar:file:/Users/Format/Develop/gitrepository/springboot-analysis/springboot-executable-jar/target/executable-jar-1.0-SNAPSHOT.jar!/lib/spring-boot-loader-1.3.5.RELEASE.jar!/org/springframework/boot/loader/JarLauncher.class
JarLauncher的执行过程
public static void main(String[] args) {
// 构造JarLauncher,然后调用它的launch方法。参数是控制台传递的
new JarLauncher().launch(args);
}
JarLauncher的launch方法:
protected void launch(String[] args) {
try {
// 在系统属性中设置注册了自定义的URL处理器:org.springframework.boot.loader.jar.Handler。如果URL中没有指定处理器,会去系统属性中查询
JarFile.registerUrlProtocolHandler();
// getClassPathArchives方法在会去找lib目录下对应的第三方依赖JarFileArchive,同时也会项目自身的JarFileArchive
// 根据getClassPathArchives得到的JarFileArchive集合去创建类加载器ClassLoader。这里会构造一个LaunchedURLClassLoader类加载器,这个类加载器继承URLClassLoader,并使用这些JarFileArchive集合的URL构造成URLClassPath
// LaunchedURLClassLoader类加载器的父类加载器是当前执行类JarLauncher的类加载器
ClassLoader classLoader = createClassLoader(getClassPathArchives());
// getMainClass方法会去项目自身的Archive中的Manifest中找出key为Start-Class的类
// 调用重载方法launch
launch(args, getMainClass(), classLoader);
}
catch (Exception ex) {
ex.printStackTrace();
System.exit(1);
}
}
// Archive的getMainClass方法
// 这里会找出spring.study.executablejar.ExecutableJarApplication这个类
public String getMainClass() throws Exception {
Manifest manifest = getManifest();
String mainClass = null;
if (manifest != null) {
mainClass = manifest.getMainAttributes().getValue("Start-Class");
}
if (mainClass == null) {
throw new IllegalStateException(
"No 'Start-Class' manifest entry specified in " + this);
}
return mainClass;
}
// launch重载方法
protected void launch(String[] args, String mainClass, ClassLoader classLoader)
throws Exception {
// 创建一个MainMethodRunner,并把args和Start-Class传递给它
Runnable runner = createMainMethodRunner(mainClass, args, classLoader);
// 构造新线程
Thread runnerThread = new Thread(runner);
// 线程设置类加载器以及名字,然后启动
runnerThread.setContextClassLoader(classLoader);
runnerThread.setName(Thread.currentThread().getName());
runnerThread.start();
}
@Override
public void run() {
try {
// 根据Start-Class进行实例化
Class> mainClass = Thread.currentThread().getContextClassLoader()
.loadClass(this.mainClassName);
// 找出main方法
Method mainMethod = mainClass.getDeclaredMethod("main", String[].class);
// 如果main方法不存在,抛出异常
if (mainMethod == null) {
throw new IllegalStateException(
this.mainClassName + " does not have a main method");
}
// 调用
mainMethod.invoke(null, new Object[] { this.args });
}
catch (Exception ex) {
UncaughtExceptionHandler handler = Thread.currentThread()
.getUncaughtExceptionHandler();
if (handler != null) {
handler.uncaughtException(Thread.currentThread(), ex);
}
throw new RuntimeException(ex);
}
}
关于自定义的类加载器LaunchedURLClassLoader
private Class> doLoadClass(String name) throws ClassNotFoundException {
// 1) Try the root class loader
try {
if (this.rootClassLoader != null) {
return this.rootClassLoader.loadClass(name);
}
}
catch (Exception ex) {
// Ignore and continue
}
// 2) Try to find locally
try {
findPackage(name);
Class> cls = findClass(name);
return cls;
}
catch (Exception ex) {
// Ignore and continue
}
// 3) Use standard loading
return super.loadClass(name, false);
}
如果根类加载器存在,调用它的加载方法。这里是根类加载是ExtClassLoader 调用LaunchedURLClassLoader自身的findClass方法,也就是URLClassLoader的findClass方法 调用父类的loadClass方法,也就是执行默认的类加载顺序(从BootstrapClassLoader开始从下往下寻找)
protected Class> findClass(final String name)
throws ClassNotFoundException
{
try {
return AccessController.doPrivileged(
new PrivilegedExceptionAction>() {
public Class> run() throws ClassNotFoundException {
// 把类名解析成路径并加上.class后缀
String path = name.replace('.', '/').concat(".class");
// 基于之前得到的第三方jar包依赖以及自己的jar包得到URL数组,进行遍历找出对应类名的资源
// 比如path是org/springframework/boot/loader/JarLauncher.class,它在jar:file:/Users/Format/Develop/gitrepository/springboot-analysis/springboot-executable-jar/target/executable-jar-1.0-SNAPSHOT.jar!/lib/spring-boot-loader-1.3.5.RELEASE.jar!/中被找出
// 那么找出的资源对应的URL为jar:file:/Users/Format/Develop/gitrepository/springboot-analysis/springboot-executable-jar/target/executable-jar-1.0-SNAPSHOT.jar!/lib/spring-boot-loader-1.3.5.RELEASE.jar!/org/springframework/boot/loader/JarLauncher.class
Resource res = ucp.getResource(path, false);
if (res != null) { // 找到了资源
try {
return defineClass(name, res);
} catch (IOException e) {
throw new ClassNotFoundException(name, e);
}
} else { // 找不到资源的话直接抛出ClassNotFoundException异常
throw new ClassNotFoundException(name);
}
}
}, acc);
} catch (java.security.PrivilegedActionException pae) {
throw (ClassNotFoundException) pae.getException();
}
}
// 注册org.springframework.boot.loader.jar.Handler URL协议处理器
JarFile.registerUrlProtocolHandler();
// 构造LaunchedURLClassLoader类加载器,这里使用了2个URL,分别对应jar包中依赖包spring-boot-loader和spring-boot,使用 "!/" 分开,需要org.springframework.boot.loader.jar.Handler处理器处理
LaunchedURLClassLoader classLoader = new LaunchedURLClassLoader(
new URL[] {
new URL("jar:file:/Users/Format/Develop/gitrepository/springboot-analysis/springboot-executable-jar/target/executable-jar-1.0-SNAPSHOT.jar!/lib/spring-boot-loader-1.3.5.RELEASE.jar!/")
, new URL("jar:file:/Users/Format/Develop/gitrepository/springboot-analysis/springboot-executable-jar/target/executable-jar-1.0-SNAPSHOT.jar!/lib/spring-boot-1.3.5.RELEASE.jar!/")
},
LaunchedURLClassLoaderTest.class.getClassLoader());
// 加载类
// 这2个类都会在第二步本地查找中被找出(URLClassLoader的findClass方法)
classLoader.loadClass("org.springframework.boot.loader.JarLauncher");
classLoader.loadClass("org.springframework.boot.SpringApplication");
// 在第三步使用默认的加载顺序在ApplicationClassLoader中被找出
classLoader.loadClass("org.springframework.boot.autoconfigure.web.DispatcherServletAutoConfiguration");
Spring Boot Loader的作用
推荐阅读:
用 M1 MacBook 当主力开发机:程序员使用半个月后如是说
请谨慎使用Arrays.asList、ArrayList的subList
微信扫描二维码,关注我的公众号
朕已阅
评论